Transforming an array into an object

I am having a really hard time understanding the reduce in this instance

 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) // {tacos: 2, pizza: 3, fries: 1, ice cream: 2}
1 Like

Which part? Does this work? Did you write it or are your trying to understand someone else’s code?

yeah i was reading on the reduce method on arrays and i don’t understand how this code works

Is there a particular spot where you get lost? This iterates over the array and adds or updates an object property for every element in that array. The object is saved into result.

the reducer function … i understand what reduce does on like an array of numbers to add them for example , but i don’t get what’s happening here

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

The reducer function is called for every element in the array. tally is the object that is being built. vote is the current element in the array. For every element (vote) if it’s already in the object, it adds to the count. Otherwise it adds it to the object.

1 Like

Thank you so much for this answer, It seems so obvious now LOL

I’m glad I could help. Happy coding!