Q:

Write a JavaScript program to group the elements of an array based on the given function and returns the count of elements in each group

0

Write a JavaScript program to group the elements of an array based on the given function and returns the count of elements in each group.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

const countBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
    acc[val] = (acc[val] || 0) + 1;
    return acc;
  }, {});
console.log(countBy([6, 10, 100, 10], Math.sqrt));
console.log(countBy([6.1, 4.2, 6.3], Math.floor));
console.log(countBy(['one', 'two', 'three'], 'length'));

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now