javascript - how to access zeroth element in reduce to count repeats in an array -
on whim of node school, trying use reduce
count number of times string repeated in 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. reason, reduce
seems skip first element. don't know why. first time through array, index
1
. tried putting in logic like, if (index === 1){//put 'prev' property of 'obj'}
. seems convoluted. i'm not how node school wants me solve problem. however, wonder what's way access zeroth element in array you're reducing. why zeroth element seemingly ignored reduction procedure? guess pass in fruits[0]
after callback start value initially. what's best way access zeroth element?
if no
initialvalue
provided,previousvalue
equal first value in array ,currentvalue
equal second.
additionally, have return value function. value becomes value of previousvalue
on next iteration.
i'd suggest "carry" aggregator obj
initial value.
var fruits = ["apple", "banana", "apple", "durian", "durian", "durian"]; var obj = fruits.reduce(function(carry, fruit){ if(!carry[fruit]) carry[fruit] = 0; // if key doesn't exist, default 0 carry[fruit]++; // increment value of key return carry; // return aggregator next iteration }, {}); alert(json.stringify(obj));
here's simple diagram:
fruit carry (before operation) carry (after operation, returned value) 1st iteration: apple {} {apple:1} 2nd iteration: banana {apple:1} {apple:1, banana:1} 3rd iteration: apple {apple:1, banana:1} {apple:2, banana:1} 4th iteration: durian {apple:2, banana:1} {apple:2, banana:1, durian:1} 5th iteration: durian {apple:2, banana:1, durian:1} {apple:2, banana:1, durian:2} 6th iteration: durian {apple:2, banana:1, durian:2} {apple:2, banana:1, durian:3}
Comments
Post a Comment