Count grouped elements

JavaScript, Array, Object · Nov 3, 2020

Groups the elements of an array based on the given function and returns the count of elements in each group.

const countBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => {
    acc[val] = (acc[val] || 0) + 1;
    return acc;
  }, {});
countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}
countBy([{ count: 5 }, { count: 10 }, { count: 5 }], x => x.count)
// {5: 2, 10: 1}

More like this

  • Group array elements

    Groups the elements of an array based on the given function.

    JavaScript, Array · Oct 22, 2020

  • Ungroup array elements based on function

    Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function.

    JavaScript, Array · Jan 23, 2022

  • Partition array in two

    Groups the elements into two arrays, depending on the provided function's truthiness for each element.

    JavaScript, Array · Nov 3, 2020