JS: Object.groupBy

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2024)

Object.groupBy(iterable, f)
  • Group items in iterable by a function's return value.
  • Return a object.
  • Keys are return value of f.
  • Each key's value is an array of items in iterable.
// group by mod 3

const xx = [1, 2, 3, 4, 5, 6, 7];
const yy = Object.groupBy(xx, (x) => x % 3);
console.log(yy);
/*
[Object: null prototype] {
  "0": [ 3, 6 ],
  "1": [ 1, 4, 7 ],
  "2": [ 2, 5 ]
}
*/

JavaScript. Group Iterable