Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use reduce to shorten array

Tags:

javascript

Use reduce to find number of times an items is in an array. The array could have arrays inside recursively.

var foo = [
  1,
  [2, 3, 4], 
  4, [5,6,7], 4
];

bar(foo, 4) would return 3.

like image 437
NorCalKnockOut Avatar asked Dec 30 '15 19:12

NorCalKnockOut


1 Answers

Try this one using Array.prototype.reduce.

var foo = [1, [2, 3, 4], 4, [5, 6, 7], 4];

function f(arr, item) {
  return arr.reduce(function (s, i) {
    if (Array.isArray(i)) return s+f(i, item);
    return s+(i==item?1:0);
  }, 0);
}

console.log(f(foo, 4))

The function f is a recursive function. We loop over all the items and reduce them to one number. The function would be called on all the inner arrays as well, and for the non-array items, we just check them to be equal to the desired item.

like image 169
Aᴍɪʀ Avatar answered Oct 17 '22 00:10

Aᴍɪʀ