0

Could someone please explain how reduce() is counting the instances of an array item and adding them to the empty object in the below code? For example, we end up with { car: 5, truck: 3 }. I don't quite understand what obj[item] is.

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

const transportation = data.reduce(function(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}
4
  • "I don't quite understand what obj[item] is." Do you understand what obj is? If not check documentation how reduce works. In any case feel free to use debugging technics: put console.log(obj) on top of the callback and you will understand how everything works. Commented Oct 3, 2017 at 11:09
  • when item==='car', obj[item] is obj['car'] or obj.car - does that help? Commented Oct 3, 2017 at 11:12
  • obj[item] is referencing an element of the obj object which is named after the current, iterative value passed to the callback. So it might translate as obj['car'], for example. Commented Oct 3, 2017 at 11:12
  • Array and Array.prototype.reduce() on MDN Commented Oct 3, 2017 at 11:12

3 Answers 3

2

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

const transportation = data.reduce(function(obj, item) {
      console.log(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}

If you can see the console output, you will see the object obj would be acting as an data structure which has keys as the element of array and value as the frequency, if the property is undefined it would be initialised to 0, in further steps we only need to increment that value.

obj[item] is the property of the object. This would be created when a unique string comes and would be initialized to 0, on every next step we would just increment this value

Note in the reduce the first arguments is the object passes on by the previous iteration (initially {}). and the 2nd would traverse through each element

Sign up to request clarification or add additional context in comments.

1 Comment

"object obj would be acting as an map": I get what you're saying but isn't this just making it more confusing. Maps are a different JS data structure.
1

in Array.prototype.reduce() you can find that first arg of callback function is accumulator. This is your obj -> the result of reduction. item is the currentValue that is being processed -> in your case is one of the strings from array data. obj[item] is used to store count of how many times has string of item vale appeared in data array.

Comments

1

Let's take a simpler example: adding all the integers in an array together.

const data = [1, 2, 3, 4, 5];
const sum = data.reduce(function(total, num) {
  return total + num;
}, 0);

reduce accepts a function that has two arguments: 1) total, the accumulator, that is passed into the next iteration of the process and which is set as 0 for the initial value, and 2) num, the current element in the iteration that's being processed.

For each iteration num is added to the total which, after the final iteration, is passed to sum (the result is 15).

In your example the empty object serves as the accumulator to which the values (items) are added as object keys.

const transportation = data.reduce(function(obj, item) {

  // if the object does not have a key matching the value
  // of item, create it and set it to zero
  // for example: obj['car'] = 0
  if (!obj[item]) {
    obj[item] = 0;
  }

  // Now we increase the value of that property because
  // we want to indicate an instance of that car, bike, truck etc
  // For example `obj['car']++`
  obj[item]++;

  // Then we return the object (accumulator) for the next
  // iteration
  return obj;
}, {});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.