JS: Map.groupBy

By Xah Lee. Date: .

(new in JS: ECMAScript 2024)

Map.groupBy(iterable, f)
  • Group items in iterable by a function's return value.
  • Return a map.
  • 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 = Map.groupBy(xx, (x) => x % 3);
console.log(yy);
// Map(3) { 1 => [ 1, 4, 7 ], 2 => [ 2, 5 ], 0 => [ 3, 6 ] }

JavaScript. Group Iterable