Tim
Tim

Reputation: 187

Array reduce function -- why do these two (what appear to be equivalent) functions return different objects

I have a an array, data, with a few items that repeat. I'm trying to use the reduce method on the array to return an object that has each item and how many times that item occurs in the data array.

The first reduction function works properly. The second one, the one I came up with, appears to me to be the same except for rather than checking for if(!obj[item]) I'm checking if(obj[item]) with an else block. I can't figure out how these two solutions differ, though they must... it seems like my (obj[item]) is never truthy, as I'm getting 0 for each item's count.

const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck'];

const transportation = data.reduce((obj, item) => {
  if (!obj[item]) {
    obj[item] = 0;
  }
  obj[item]++;
  return obj;
}, {});
console.log(transportation); //  {car: 5, truck: 3, bike: 2, walk: 2, van: 2}


var instances = data.reduce((totalObj, item) => {
  if (totalObj[item]) {
    totalObj[item]++;
  } else {
    totalObj[item] = 0;
  }
  return totalObj;
}, {});

console.log(instances); // {car: 0, truck: 0, bike: 0, walk: 0, van: 0}

Upvotes: 1

Views: 30

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386730

You need to initialize the property with 1, because you want to count and zero is falsy.

totalObj[item] = 1;

const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];

var instances = data.reduce((totalObj, item) => {
  if (totalObj[item]) {
    totalObj[item]++;
  } else {
    totalObj[item] = 1;
  }
  return totalObj;
}, {});

console.log(instances);

Upvotes: 3

Related Questions