TechEarl

Modern JavaScript Array Methods: at, flat, toReversed, and groupBy

The JavaScript array methods worth reaching for in 2026, with the tasks they solve: convert and fill arrays, at() and flat(), merge, insert at an index, the copying toReversed/toSorted/toSpliced/with, dedupe with Set, random picks and a correct shuffle, reduce, and Object.groupBy (not the Array.prototype.group that never shipped).

Ishan KarunaratnePublished ⏱️ 21 min readUpdated
Share thisCopied
JavaScript array methods in 2026: at, flat, toSorted, toSpliced, merge, insert, dedupe with Set, a Fisher-Yates shuffle, reduce, and Object.groupBy.

The JavaScript array methods worth knowing in 2026: at() for negative indexing, flat(Infinity) for deep flattening, the copying toReversed, toSorted, toSpliced and with that reorder without mutating, Object.groupBy for grouping, and reduce for genuine folds. This page also covers the everyday tasks built on them: converting and filling arrays, merging, inserting at an index, removing duplicates, and picking or shuffling randomly.

One correction up front, because a lot of older posts (mine included, once) get it wrong: Array.prototype.group was renamed and never shipped. The real API is Object.groupBy. Below is what is real now, with the browser and Node floor for each method.

Array.from vs spread

A NodeList from querySelectorAll, the arguments object, an HTMLCollection, a Set, a Map, a string: none of these is an Array. People try .map() on a NodeList and get TypeError: nodeList.map is not a function. They are either array-like (numeric indexes plus a length, but no array methods) or iterable (they work in for...of). To get the methods on this page, convert first with Array.from(x) or spread [...x]:

javascript
const divs = Array.from(document.querySelectorAll('div')); // NodeList -> Array
const items = [...new Set([1, 2, 2, 3])];                   // Set -> Array, [1,2,3]
const chars = [...'hello'];                                 // String -> Array, ['h','e','l','l','o']

The old way was Array.prototype.slice.call(arguments), which reads like the workaround it is. Array.from and spread replaced it years ago and are Baseline on every runtime you will meet today. The two are interchangeable most of the time, with one real difference:

  • Spread only works on iterables. [...x] needs x to implement the iterator protocol (arrays, strings, Sets, Maps, NodeLists, generators).
  • Array.from handles both iterables and array-likes. It accepts anything with a numeric length, even an object that is not iterable at all:
javascript
const arrayLike = { 0: 'a', 1: 'b', length: 2 };

Array.from(arrayLike); // ['a', 'b']
[...arrayLike];        // TypeError: arrayLike is not iterable

The bigger reason to keep Array.from around is its second argument, a map function applied as the array is built. MDN documents the callback as receiving the element and its index, exactly like Array.prototype.map. Spread cannot do this:

javascript
// Convert AND transform in one pass:
const lengths = Array.from(document.querySelectorAll('p'), p => p.textContent.length);

With spread you would write [...nodes].map(...), which builds an intermediate array and then maps it. For a handful of nodes the difference is academic, but the single-pass form states the intent more directly. The same callback is what makes Array.from a range builder, covered in the next section.

For the arguments object specifically, you should not need to convert at all. Rest parameters give you a real array directly:

javascript
function sum(...args) {
  return args.reduce((a, b) => a + b, 0);
}

args is already an Array. Rest params also work in arrow functions (which have no arguments binding) and make the signature self-documenting. I only touch arguments when maintaining old code.

You haveIterable?SpreadArray.from(x)Notes
NodeList / arrayyesworksworkseither is fine
Set / Mapyesworksworksspread is terser
Stringyesworksworkssplits into code points
argumentsyesworksworksprefer ...args instead
array-like with only lengthnothrowsworksArray.from only
Need to map while converting-noworksArray.from(x, fn)

My rule of thumb: [...x] for a quick copy of something iterable, Array.from for a non-iterable array-like or when you want to transform in the same pass. Both produce a fresh, shallow copy.

Fill an array or build a number range

To fill an array with the same value, use Array(n).fill(value). To build a number sequence, use Array.from({length: n}, (_, i) => start + i). They look interchangeable, but fill puts the same value in every slot, while the sequence builder runs a function per index so each slot is computed fresh.

javascript
Array(5).fill(0);                          // [0, 0, 0, 0, 0]
Array.from({length: 5}, (_, i) => i);      // [0, 1, 2, 3, 4]
Array.from({length: 5}, (_, i) => i + 1);  // [1, 2, 3, 4, 5]

Array(n) on its own gives you an array of length n with no actual elements (the slots are holes), and map and forEach skip holes, so you cannot transform it. fill materializes every slot. For primitives (numbers, strings, booleans, null) that is perfect, because each slot holds an independent copy of the value.

The fill reference trap

It breaks the moment the fill value is an object. fill takes one value and writes that same value into every position, so an object or array gives you n references to one shared object:

javascript
const rows = Array(3).fill([]);
rows[0].push("a");
console.log(rows);  // [["a"], ["a"], ["a"]]  -- all three changed

There is one array in memory and all three slots point at it. When you want distinct objects, use Array.from with a callback, which runs once per index:

javascript
const rows = Array.from({length: 3}, () => []);
rows[0].push("a");
console.log(rows);  // [["a"], [], []]  -- only the first changed

Same pattern for objects: Array.from({length: 3}, () => ({})) (the parentheses keep the parser from reading the braces as a function body).

Ranges, steps and partial fills

javascript
// a range from `start` (inclusive) of length `n`
const range = (start, n) => Array.from({length: n}, (_, i) => start + i);
range(5, 4);   // [5, 6, 7, 8]

// with a step
const step = (start, n, by) => Array.from({length: n}, (_, i) => start + i * by);
step(0, 5, 10);  // [0, 10, 20, 30, 40]

You will also see the older Array(n).fill().map((_, i) => i). It works, but it makes two passes: fill() materializes the holes, then map builds the result. Array.from with a mapper does it in one pass, so I use it for sequences and keep fill for the constant case.

fill also takes optional start and end indices (end is exclusive, same as slice), and it mutates the array in place and returns it:

javascript
const a = [1, 2, 3, 4, 5];
a.fill(0, 1, 3);   // [1, 0, 0, 4, 5]  -- indices 1 and 2
a.fill(9, 3);      // [1, 0, 0, 9, 9]  -- index 3 to the end
a.fill(7);         // [7, 7, 7, 7, 7]  -- whole array

Negative indices count from the end (a.fill(0, -2) fills the last two slots). Because fill returns the same array, const b = a.fill(0) leaves b and a pointing at the one mutated array. It is one more case of the mutation trap below.

at() for negative indexing

To read the last element of an array you used to write arr[arr.length - 1]. It works, but it is noisy and easy to fat-finger. at() takes a negative index and counts from the end:

javascript
const parts = ["a", "b", "c"];
parts.at(-1); // "c"
parts.at(-2); // "b"
parts[parts.length - 1]; // "c", the old way

Bracket access does not understand negative numbers (arr[-1] is just a property lookup that returns undefined), which is exactly the trap at() removes. It also works on strings and typed arrays, so "hello".at(-1) is "o". at() has been Baseline since 2022 (Chrome 92, Firefox 90, Safari 15.4, Node 16.6), so on any current runtime you can reach for it without a second thought.

flat() and flatMap()

flat() flattens nested arrays. The default depth is 1, so it only unwraps one level. For an arbitrarily deep structure, pass Infinity:

javascript
[1, [2, [3, [4]]]].flat();         // [1, 2, [3, [4]]]  (depth 1)
[1, [2, [3, [4]]]].flat(2);        // [1, 2, 3, [4]]
[1, [2, [3, [4]]]].flat(Infinity); // [1, 2, 3, 4]

That flat(Infinity) line is the whole answer to "how do I recursively flatten a nested array in JavaScript." It supersedes the hand-rolled recursive helpers and library flatten functions that older code carried around.

flatMap() maps each element and then flattens the result by exactly one level. It is the idiomatic way to expand-or-drop items in one pass: return an array of several items to expand, or an empty array to drop:

javascript
const te_words = (s) => s.split(" ");
["the lazy dog", "fox"].flatMap(te_words);
// ["the", "lazy", "dog", "fox"]

// Drop odd numbers, double the even ones, in one pass:
[1, 2, 3, 4].flatMap((n) => (n % 2 ? [] : [n * 2]));
// [4, 8]

Both have been Baseline since 2020 (Node 11+), so they are safe everywhere.

Merge two arrays

To merge two arrays into a new array, use spread: [...a, ...b]. To append b into an existing array a, use a.push(...b). a.concat(b) also returns a new array, and unlike a.push(...b) it never runs into the argument-count limit described below. The right pick depends on whether you want to mutate, and how big the arrays are.

javascript
const a = [1, 2, 3];
const b = [4, 5, 6];

const merged = [...a, ...b];   // [1, 2, 3, 4, 5, 6], new array, a and b untouched
a.push(...b);                  // a is now [1, 2, 3, 4, 5, 6], b untouched
const copy = a.concat(b);      // new array, a and b untouched (a is still the pushed version above)

Spread is my default. The originals are never modified, the order is exactly a then b, and it composes with more sources and single values: [...front, "x", ...back]. The cost is a new array of a.length + b.length, so for a moment you hold the originals plus the result.

a.push(...b) mutates a and returns the new length, with no second array allocated. It is the modern form of the old Array.prototype.push.apply(a, b) trick. Use it only when mutating a is what you want; if a is shared state or a prop, copy-merge instead.

concat returns a new array and flattens one level of any array argument:

javascript
[1, 2].concat([3, 4]);   // [1, 2, 3, 4]   array arg is flattened one level
[1, 2].concat(3, 4);     // [1, 2, 3, 4]   plain values appended
[1, 2].concat([[3, 4]]); // [1, 2, [3, 4]] only ONE level is flattened

The spread arg-count gotcha

a.push(...b) and f(...b) expand b into individual function arguments, and engines cap how many arguments one call can take. The limit is unspecified and varies with engine, version and available stack: JavaScriptCore (Safari) hard-codes 65,536 arguments, and on my machine (Node 26, V8) a push(...b) of 120,000 elements worked while 125,000 threw RangeError: Maximum call stack size exceeded. Do not design around any particular number; I treat anything in the tens of thousands as the danger zone.

javascript
const huge = new Array(200_000).fill(0);
const target = [];
target.push(...huge); // RangeError on V8: too many spread arguments overflow the call stack

An array literal is different. [...a, ...b] spreads into a new array, not into a function call, so it is not subject to the argument-count limit; it is bounded only by memory and the maximum array length. For large arrays, just do not spread into a call:

javascript
// Loop append, in place, no arg-count risk:
function te_extend(target, source) {
  for (let i = 0; i < source.length; i++) target.push(source[i]);
  return target;
}

// Or copy-merge without spread:
const merged = a.concat(b); // safe at any size
TechniqueMutates?Allocates new array?Safe for very large arrays?Reach for it when
[...a, ...b]NoYesYes (not a function call, so no arg-count limit)You want a new merged array; readability matters
a.push(...b)Yes (a)NoNo (arg-count limit)You own a and want it extended in place
a.concat(b)NoYesYesYou want a copy, or the arrays are very large
loop pushYes (a)NoYesIn-place merge of very large arrays

None of these deduplicate: merging [1, 2] and [2, 3] gives [1, 2, 2, 3]. For unique values, merge then remove duplicates. For objects rather than arrays, see merging objects in JavaScript.

The mutation trap: copying methods vs in-place methods

This is the part that bites people, so it gets the most space. reverse(), sort(), and splice() all mutate the array in place and return a reference to it (or, for splice, the removed elements). The return value lulls you into thinking you got a fresh array. You did not:

javascript
const scores = [3, 1, 2];
const reversed = scores.reverse();
// reversed is [2, 1, 3] ... and so is scores, now also [2, 1, 3].
// You just mutated the original while trying to make a copy.

If scores came in as a function argument, a prop, or a value someone else still holds a reference to, you have introduced a bug that shows up far from where you wrote it. The same trap applies to sort() (which also mutates) and splice().

The old fix was to copy first, then mutate the copy:

javascript
const reversed = [...scores].reverse(); // scores untouched
const sorted = [...scores].sort((a, b) => a - b);

Since ES2023 there is a cleaner fix: a copying counterpart for each mutating method. toReversed(), toSorted(), toSpliced(), and with() all leave the original alone and return a new array:

javascript
const scores = [3, 1, 2];

const reversed = scores.toReversed();          // [2, 1, 3]
const sorted   = scores.toSorted((a, b) => a - b); // [1, 2, 3]
const patched  = scores.with(0, 99);           // [99, 1, 2]  (replace index 0)
const spliced  = scores.toSpliced(1, 1);       // [3, 2]      (remove 1 at index 1)

scores; // [3, 1, 2] throughout. Nothing above touched it.

with(index, value) is the copying replacement for arr[index] = value: it returns a new array with one element swapped, which is exactly what you want in a React setState or any immutable update. toSpliced(start, deleteCount, ...items) mirrors splice() for inserting and removing (the next section covers inserting in detail).

The trade-off is honest: the copying methods allocate a new array every call, so in a tight loop over a huge array the in-place version is cheaper. For ordinary application code the readability and the absence of spooky-action-at-a-distance bugs win easily.

These four are ES2023, Baseline since 2023: Chrome 110, Firefox 115, Safari 16, Node 20+. If you ship to runtimes older than that (Node 18, old Safari), keep using the spread-then-mutate form or a polyfill.

Insert an item at a specific index

To insert an item into an array at a specific index, use splice(index, 0, item) to mutate in place, or toSpliced(index, 0, item) to get a new array and leave the original untouched:

javascript
const months = ["Jan", "Mar", "Apr"];

// Mutates `months`, returns the removed elements ([] here):
months.splice(1, 0, "Feb");
// months is now ["Jan", "Feb", "Mar", "Apr"]

// Copies: returns a new array, the original is unchanged:
const original = ["Jan", "Mar", "Apr"];
const updated = original.toSpliced(1, 0, "Feb");
// updated is ["Jan", "Feb", "Mar", "Apr"], original is still ["Jan", "Mar", "Apr"]

The 0 is the part people forget. The signature is (start, deleteCount, ...items), a delete-and-insert in one call, and a delete count of 0 means "delete nothing, just insert here." Both methods share it.

The most common splice mistake is the return value. splice returns the array of removed elements, not the new array:

javascript
const arr = [1, 2, 4];
const result = arr.splice(2, 0, 3);
// arr === [1, 2, 3, 4]   (the insert)
// result === []          (nothing was removed)

If you wrote const updated = arr.splice(2, 0, 3) expecting the new array, updated is [] and arr was silently mutated. toSpliced returns the new array instead, which is what you want in React state updates, Redux reducers, or anywhere you should not mutate:

javascript
const arr = [1, 2, 4];
const updated = arr.toSpliced(2, 0, 3);
// updated === [1, 2, 3, 4]
// arr     === [1, 2, 4]   (untouched)

Negative and out-of-range indexes behave the same in both. A negative start counts back from the end, so splice(-1, 0, x) inserts before the last element:

javascript
const arr = ["a", "b", "d"];
arr.splice(-1, 0, "c");   // ["a", "b", "c", "d"]

A start past the end clamps to the length, so the item lands on the end (like push). A non-zero delete count replaces instead of inserting: arr.splice(1, 1, "x") deletes one element at index 1 and puts "x" there.

If you cannot rely on Node 20, a spread one-liner gives the same copy semantics anywhere:

javascript
function teInsertAt(arr, index, item) {
  return [...arr.slice(0, index), item, ...arr.slice(index)];
}

teInsertAt([1, 2, 4], 2, 3);   // [1, 2, 3, 4]

For the ends, [item, ...arr] prepends and [...arr, item] appends.

Older tutorials (this topic originally followed that style on my site too) suggest adding an Array.prototype.insert method. Do not. A property you add can clash with a future native method of the same name, and it leaks onto every array in the program, including ones from libraries you did not write (a careless for...in will even iterate it). The grouping saga below is the real-world proof. Keep the helper as a plain function like teInsertAt, or use toSpliced directly.

Remove duplicates from an array

To remove duplicate values from an array of primitives, wrap it in a Set and spread it back:

javascript
const ids = [4, 4, 8, 15, 16, 16, 23, 42, 42];
const unique = [...new Set(ids)]; // [4, 8, 15, 16, 23, 42]

That is the whole answer for numbers, strings, booleans, null, undefined, and symbols. A Set stores each value once and iterates in insertion order, so the result keeps first-seen order. If you only need to count distinct values or test membership, skip the spread: new Set(ids).size is the count, and set.has(x) is an O(1) check, far cheaper than array.includes(x) in a loop.

Array.from(new Set(arr)) is equivalent and predates spread, but in 2026 there is no compatibility reason to prefer it (Set, Array.from and spread all date to ES2015). It earns its place when you want to map in the same pass: Array.from(new Set(arr), (x) => x * 2).

NaN and signed zero

Set compares values with SameValueZero, which behaves like === with one deliberate exception:

  • NaN deduplicates. Under ===, NaN === NaN is false, so a hand-rolled filter(indexOf) dedupe leaves duplicate NaNs in. SameValueZero treats every NaN as the same value.
  • +0 and -0 collapse to one entry. +0 === -0 is already true, so SameValueZero agrees. Object.is (SameValue) is the comparison that keeps them apart.
javascript
[...new Set([NaN, NaN])]; // [NaN]    one entry
[...new Set([0, -0])];    // [0]      one entry

Dedupe an array of objects

The one-liner silently fails on objects, because Set compares objects by reference, not contents:

javascript
const users = [
  { id: 1, name: "Ada" },
  { id: 2, name: "Linus" },
  { id: 1, name: "Ada" },
];

[...new Set(users)].length; // 3   nothing was removed

Dedupe by a key you care about instead. A Map keyed on that property overwrites earlier entries with the same key, and .values() gives back one object per key:

javascript
const byId = [...new Map(users.map((u) => [u.id, u])).values()];
// [ { id: 1, name: "Ada" }, { id: 2, name: "Linus" } ]

This keeps the last object seen per id. To keep the first, reverse before building the map, or guard with if (!map.has(u.id)) map.set(u.id, u) in a loop. I keep a small helper for it:

javascript
const teUniqueBy = (arr, keyFn) =>
  [...new Map(arr.map((item) => [keyFn(item), item])).values()];

teUniqueBy(users, (u) => u.id); // deduped by id

To dedupe by the whole object, you can key on JSON.stringify(it), but it is key-order sensitive ({a: 1, b: 2} and {b: 2, a: 1} serialize differently) and drops undefined values and functions. Fine for a small fixed shape; for arbitrary objects, key on a real id.

Get a random item and shuffle an array

To get a random item from an array, index it with a floored random multiple of its length:

javascript
const fruits = ["apple", "banana", "cherry", "date"];
const pick = fruits[Math.floor(Math.random() * fruits.length)];

Math.random() returns a float from 0 (inclusive) to 1 (exclusive), so multiplying by length and flooring gives a valid index from 0 to length - 1, with no off-by-one to guard against. I wrap it in a helper (Lodash calls the same operation _.sample):

javascript
const teSample = (arr) => arr[Math.floor(Math.random() * arr.length)];

teSample(["heads", "tails"]); // "heads" or "tails"

On an empty array it returns undefined. For n distinct items, do not call it in a loop (that can repeat items); shuffle and slice instead.

Shuffle correctly with Fisher-Yates

The shuffle pasted into a hundred answers is broken:

javascript
// WRONG: biased, do not use
const bad = arr.sort(() => Math.random() - 0.5);

sort does not call the comparator a uniform number of times per element, so some orderings come up far more often than others and elements tend to stay near where they started. The correct shuffle is Fisher-Yates (the Durstenfeld form): walk from the end and swap each position with a random earlier-or-equal one.

javascript
const teShuffle = (arr) => {
  const out = [...arr]; // copy so the original is untouched
  for (let i = out.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [out[i], out[j]] = [out[j], out[i]];
  }
  return out;
};

It runs in O(n) and produces every permutation with equal probability. The i + 1 matters: each element must be allowed to swap with itself, and getting that bound wrong reintroduces bias. To draw n distinct items: teShuffle(arr).slice(0, n).

When Math.random is the wrong tool

Math.random() is not cryptographically secure; per MDN its values must not be used for anything security-related. If the pick must be unguessable (a reset token, a raffle someone could game, a real-money card shuffle), use the Web Crypto API:

javascript
// Cryptographically secure random index
const teSecureSample = (arr) => {
  const buf = new Uint32Array(1);
  crypto.getRandomValues(buf);
  return arr[buf[0] % arr.length];
};

crypto.getRandomValues() is available in browsers and in Node.js as globalThis.crypto (how Web Crypto works in Node). The % arr.length adds a small modulo bias when the length does not evenly divide 2^32; for a provably uniform pick, use rejection sampling (discard values in the unusable top slice and draw again). Cosmetic randomness, Math.random(); anything an adversary benefits from predicting, crypto.getRandomValues().

Array.reduce explained

reduce walks an array left to right, carrying a running value (the accumulator) from one element to the next, and returns that single final value. It folds a list down into one thing, and that thing can be a number, a string, an object, a Map, or another array.

javascript
const nums = [3, 1, 4, 1, 5];
const sum = nums.reduce((acc, current) => acc + current, 0);
// 14

Whatever the callback returns becomes the accumulator for the next element. The 0 is the initial value, and it is where most reduce bugs live.

Always pass the initial value

Call reduce with no initial value on an empty array and it throws:

javascript
[].reduce((a, b) => a + b);
// Uncaught TypeError: Reduce of empty array with no initial value

Without a seed, reduce uses the first element as the starting accumulator and iterates from index 1. An empty array has no first element, so it throws rather than guessing. With a seed, the empty case returns the seed: [].reduce((a, b) => a + b, 0) is 0. The seed also pins the accumulator's type from step one (a number for a sum, {} or new Map() for a build-up). My rule: every reduce gets an explicit second argument.

For money, remember these are IEEE-754 floats (0.1 + 0.2 is not 0.3), so sum integer cents and divide at the end.

Build an object or a Map

Reduce earns its keep when the result is not a scalar, such as a lookup keyed by id:

javascript
const users = [
  { id: 7, name: "Ada" },
  { id: 12, name: "Linus" },
];

const byId = users.reduce((acc, user) => {
  acc[user.id] = user;
  return acc;
}, {});
// { 7: {id:7,name:"Ada"}, 12: {id:12,name:"Linus"} }

The callback must return acc every step. Returning a fresh object with spread ({ ...acc, [user.id]: user }) avoids mutation but allocates a new object per element and is genuinely slower on large arrays, so for a plain build-up I mutate the accumulator. A Map is often the better target (insertion order, any key type, no prototype keys), and since set returns the Map the callback collapses to one expression:

javascript
const byIdMap = users.reduce(
  (acc, user) => acc.set(user.id, user),
  new Map()
);

Reach for the named method first

reduce is the most general array method, which is exactly why it is overused. A reduce that only transforms each element is a map; one that keeps a subset is a filter; one that groups by a key is Object.groupBy (next section); one that flattens is flat. The named method tells the next reader what is happening without parsing a callback. Reduce is the right call for a genuine fold, where the computation needs the running result: a sum, a product, a min/max, a running balance. The fold I write most:

javascript
const teSumBy = (arr, key) => arr.reduce((acc, item) => acc + item[key], 0);

teSumBy([{ qty: 2 }, { qty: 5 }], "qty"); // 7

Grouping: Object.groupBy and Map.groupBy (not Array.prototype.group)

Here is the correction. For years the grouping proposal was written up as a prototype method. It first tried to land as Array.prototype.groupBy, which collided with an incompatible groupBy that the Sugar library had monkey-patched onto live sites; the rename to Array.prototype.group then broke code that used arrays as ad-hoc hashmaps. So TC39 moved the feature off the prototype entirely and onto static methods. Array.prototype.group and groupToMap never shipped to any stable browser. If a tutorial tells you to call arr.group(...), it is teaching an API that does not exist.

The real API is Object.groupBy(items, callbackFn):

javascript
const teams = [
  { name: "Arsenal", tier: "top" },
  { name: "Spurs", tier: "mid" },
  { name: "City", tier: "top" },
];

const byTier = Object.groupBy(teams, ({ tier }) => tier);
// {
//   top: [{ name: "Arsenal", ... }, { name: "City", ... }],
//   mid: [{ name: "Spurs", ... }],
// }

The callback returns the group key for each element; Object.groupBy collects the elements into arrays under those keys. One useful detail: the object it returns has a null prototype (Object.create(null)), so there is no risk of a group key like "constructor" or "__proto__" colliding with inherited properties.

This replaces the reduce-to-grouped-object pattern you still see everywhere:

javascript
const products = [
  { name: "cap", type: "hat" },
  { name: "beanie", type: "hat" },
  { name: "tee", type: "shirt" },
];

// The old reduce-to-grouped-object pattern:
const grouped = products.reduce((acc, p) => {
  (acc[p.type] ??= []).push(p);
  return acc;
}, {});

// The same thing with Object.groupBy:
const grouped2 = Object.groupBy(products, (p) => p.type);

Use Map.groupBy when your group key is not a string (an object, a number you want to keep as a number, anything). It returns a Map, and Map keys can be any value:

javascript
const odd = { label: "odd" };
const even = { label: "even" };
const byParity = Map.groupBy([1, 2, 3, 4], (n) => (n % 2 ? odd : even));
byParity.get(odd);  // [1, 3]
byParity.get(even); // [2, 4]

(Object.groupBy would coerce those object keys to the string "[object Object]" and merge them, which is why Map.groupBy exists.) Note that both are static methods. You call Object.groupBy(arr, fn), never arr.groupBy(fn).

Support is the newest thing on this page: Baseline since March 2024, Chrome/Edge 117, Firefox 119, Safari 17.4, Node 21+. On older runtimes the reduce fold above still does the job.

Support at a glance

MethodFirst BaselineNode floorMutates?
at()202216.6No
flat() / flatMap()202011No
toReversed() / toSorted() / toSpliced() / with()202320No (copying)
reverse() / sort() / splice()alwaysanyYes (in place)
Object.groupBy() / Map.groupBy()202421No

A NodeList is iterable but not an Array, so it has no map, filter, or reduce. Convert it first with Array.from(nodeList) or [...nodeList]. Modern NodeList does have forEach, which trips people up, but the rest of the array methods still need a real array.

Merge first, then dedupe: [...new Set([...a, ...b])] works for primitives. For arrays of objects, dedupe by a key with a Map, because Set compares objects by reference.

Marginally, and almost never enough to matter. The real cost is the spread-into-a-new-object pattern ({ ...acc, [k]: v }) inside a reduce, which allocates a fresh object every iteration and is genuinely O(n squared)-ish on large arrays. Mutate the accumulator and return it instead.

See also

Sources

Authoritative references this article was fact-checked against.

TagsJavaScriptarray methodstoSplicedObject.groupByArray.fromreduceSetspread operatorimmutable arraysES2023

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

How JavaScript promises work: states, async/await, Promise.all vs allSettled vs race vs any, concurrency limits, polling, debounce and throttle, and mistakes.

JavaScript Promises Explained: A Complete Guide

How JavaScript promises actually work: the three states, .then/.catch/.finally, async/await, Promise.all vs allSettled vs race vs any, limiting concurrency with a promise pool, sleep and polling, debounce and throttle, what async functions desugar to, and the promise mistakes that bite in production.