you-dont-need / You-Dont-Need-Lodash-Underscore

List of JavaScript methods which you can use natively + ESLint Plugin
MIT License
18.61k stars 813 forks source link

More uses of `Object.groupBy` — `countBy`, `partition`, simpler version of `chunk` #397

Open lionel-rowe opened 3 months ago

lionel-rowe commented 3 months ago
function chunk(input, size) {
  return Object.values(
    Object.groupBy(input, (_, i) => Math.floor(i / size))
  );
}

function countBy(input, fn) {
  return Object.fromEntries(
    Object.entries(Object.groupBy(input, fn)).map(([k, v]) => [k, v.length])
  );
}

function partition(input, fn) {
  const results = Object.groupBy(input, (x) => Boolean(fn(x)))
  return [results.true ?? [], results.false ?? []]
}