On a function of grouping statistics


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;
  }, {});
countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
countBy(["one", "two", "three"], "length"); // {3: 2, 5: 1}

my question is how it works in map. arr.map () is mainly because the result of this ternary expression should be entered into fn , rather than the following reduce asking the boss to focus on explaining this

.
Jan.19,2022

  

array.map takes a function as an argument, returns a new array, and each item in the new array is the function-processed return value of the original array. In map, if fn is a function, it is fn (array [I]). If it is not a function, it returns array [I] .length

.
Menu