Siddharth Arora Siddharth Arora - 3 months ago 9
Javascript Question

Converting Array to Object using Reduce

Can someone explain how this is working.

Learning to use Array.reduce()

var votes = ['tacos','pizza','pizza','tacos','fries','ice cream','ice cream','pizza'];

var initialValue = {}

var reducer = function(tally, vote) {
if (!tally[vote]) {
tally[vote] = 1;
} else {
tally[vote] = tally[vote] + 1;
}
return tally;
}

var result = votes.reduce(reducer, initialValue)

Answer

Basically Array.prototype.reduce() method applies a function against an accumulator and each value of the array to reduce it to a single value.

In your example the reduced value (the result of a count operation) is assigned as a property of an object called tally which is returned by .reduce();

I comment your with a brief explanation:

// your data in an array
var votes = ['tacos','pizza','pizza','tacos','fries','ice cream','ice cream','pizza'];
    // optional value to use as the first argument to the first call of the callback when using Array.prototype.reduce(). 
    var initialValue = {}
    // tally = previousValue and vote = currentValue  
    var reducer = function(tally, vote) {
      // if tally is not assign as a key in tally object, add key and add value of one, (basically count 1 for one element in your votes array)
      if (!tally[vote]) {
          tally[vote] = 1;
      } else {
          // otherwise if tally object has already this key, increment its value by one, (basically it counts how many times each item in votes array is present in the array)
          tally[vote] = tally[vote] + 1;
      }
          return tally;
      }
    
    var result = votes.reduce(reducer, initialValue);
    console.log(result);

Notes: you can actually avoid using of declaring a variable for initialValue and instead using only var result = votes.reduce(reducer, {});

API documentation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Some more examples and brief explanation:

https://www.airpair.com/javascript/javascript-array-reduce

Comments