On the whim of node school, I am trying to use reduce
to count the number of times a string is repeated in an array.
var fruits = ["Apple", "Banana", "Apple", "Durian", "Durian", "Durian"],
obj = {};
fruits.reduce(function(prev, curr, index, arr){
obj[curr] ? obj[curr]++ : obj[curr] = 1;
});
console.log(obj); // {Banana: 1, Apple: 1, Durian: 3}
is sort of working. For some reason, reduce
seems to skip the first element. I don't know why. Its first time through the array, index
is 1
. I tried putting in some logic like, if (index === 1){//put 'prev' as a property of 'obj'}
. But that seems really convoluted. I'm certain that this is not how node school wants me to solve this problem. However, I wonder what's a good way to access the zeroth element in the array you're reducing. Why is this zeroth element seemingly ignored by the reduction procedure? I guess I could pass in fruits[0]
after the callback so I start with that value initially. What's the best way to access this zeroth element?
prev
because you didn't start with a seed. In subsequent calls,prev
will hold the previous return value, but you're returning nothing. – Monique.forEach()
. – Monique