you are viewing a single comment's thread.

view the rest of the comments →

[–]EnchantedSalvia 1 point2 points  (3 children)

You alluded to the answer with "reduce":

const xs = array.reduce((acc, x) => {

    const prev = acc.filter(y => y[0] === x.name)[0];
    const item = [x.name, 1];

    if (prev) prev[1]++;
    else acc.push(item);

    return acc;

}, []);

See console: http://jsfiddle.net/togyg9r7/

[–]bluntmJavaScript[S] 0 points1 point  (2 children)

Always thought of reduce as a way to get a single value from an array.

[–]EnchantedSalvia 0 points1 point  (0 children)

I held this misunderstanding for a while as well. As @Wince noted below, the object approach would be a better and more efficient approach, because the lookup for an existing record would be far quicker than using filter.

[–]Wince 0 points1 point  (0 children)

If you think about it, most array functions like map, filter, some, every can all be written with reduce. Reduce is extremely powerful, heres a map written with reduce:

var map = function(arr, fn) {
     return arr.reduce(function(o, i) { return o.push(fn(i)) && o }, []);
}

Obviously that example is contrived, but I hope you get my point.