Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 156 ยท Arrays

Array Recipes

Practical JavaScript array recipes: group with Object.groupBy, remove duplicates, flatten with flat and flatMap, chunk, zip and build arrays with Array.from.

You now know the core array methods: adding and removing items, map, filter and reduce, searching and sorting. Real programs combine them into small, repeatable patterns: "group these orders by status", "remove duplicate tags", "split this list into pages of ten".

This lesson is a cookbook of those patterns. Each recipe is short enough to remember, and each one uses either a built-in method or a few lines of code you can paste into any project. Where a recipe uses a newer feature, you will find an honest note about support and a fallback.

Building arrays with Array.from

Array.from() turns anything array-like or iterable into a real array: a string, a Set, a Map, a NodeList, or an object with a length. Its optional second argument is a mapping function, applied to each item as the array is built.

That makes it the standard way to create an array of a given size:

JS Array.from recipes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The object { length: 5 } has no items, so the first argument to the mapping function is always undefined. By convention you name it _ and use only the index i.

Don't fill with objects. Array(3).fill([]) puts the same array in every slot, so changing one row changes them all. Use Array.from with a function, as in the grid above, so each slot gets a new object.

Grouping with Object.groupBy

Grouping means splitting a list into buckets by some key: tasks by status, people by city, numbers by "even" or "odd". Object.groupBy(items, callback) does this in one call. The callback returns the key for each item, and the result is an object whose properties are arrays.

Map.groupBy() works the same way but returns a Map, which is useful when your keys are not strings (objects, numbers you want to keep as numbers, dates).

JS Object.groupBy and Map.groupBy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two details matter. The object returned by Object.groupBy has a null prototype, so it has no inherited methods such as toString or hasOwnProperty. Use Object.keys(), Object.entries() or Object.hasOwn() with it. And a group only exists if at least one item landed in it, so check before you read: byStatus.blocked ?? [].

Support: Object.groupBy() and Map.groupBy() are part of ES2024. They work in Chrome and Edge 117+, Firefox 119+, Safari 17.4+ and Node.js 21+. Older browsers (and some older company machines) do not have them. If you need to support those, use the reduce fallback below.

The fallback: grouping with reduce

Before groupBy existed, everyone wrote this, and you will see it in plenty of codebases:

JavaScript
function groupBy(items, getKey) {
  return items.reduce((groups, item) => {
    const key = getKey(item);
    (groups[key] ??= []).push(item);
    return groups;
  }, {});
}

The ??= operator creates the array the first time a key appears (see logical assignment).

Counting occurrences

Counting is grouping where you only keep the size of each bucket. A plain object or a Map works as the tally:

JS Counting with reduce

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Unique values

A Set only stores each value once, so spreading a Set back into an array is the shortest way to remove duplicates:

JavaScript
const unique = [...new Set(values)];

This compares values the way === does (with one exception: NaN counts as equal to itself). That works for numbers and strings, but two objects with identical contents are still two different objects. To remove duplicate objects by a key, keep the first or last one per key in a Map:

JS Removing duplicates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The filter version works because seen.add() returns the set itself, which is truthy, so the item is kept the first time its id appears.

Flattening with flat and flatMap

flat() removes one level of nesting from an array of arrays. Pass a depth to go deeper, or Infinity to flatten everything:

JavaScript
[[1, 2], [3], [4, 5]].flat();      // [1, 2, 3, 4, 5]
[1, [2, [3, [4]]]].flat(2);        // [1, 2, 3, [4]]
[1, [2, [3, [4]]]].flat(Infinity); // [1, 2, 3, 4]

flatMap(fn) is map(fn) followed by flat() with depth 1. It shines when each item produces zero, one or many results, because returning [] drops an item and returning several values expands it:

JS flat and flatMap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Chunking

Chunking splits an array into groups of a fixed size, for pages, table rows or batches of network requests. There is no built-in method, but Array.from makes it a one-liner: work out how many chunks you need, then slice each one.

JavaScript
function chunk(array, size) {
  return Array.from({ length: Math.ceil(array.length / size) }, (_, i) =>
    array.slice(i * size, i * size + size)
  );
}

chunk([1, 2, 3, 4, 5, 6, 7], 3); // [[1, 2, 3], [4, 5, 6], [7]]

The last chunk is simply shorter when the items don't divide evenly.

Zipping

Zipping pairs up items from two (or more) arrays by position: names with scores, labels with values. Map over one array and use the index to read the other:

JS Chunk, zip and partition

Press Run (or Ctrl + Enter) to see the console output here.

No output.

zip stops at the shorter array so it never invents undefined values. Partition is the last recipe in the example: it is like grouping, but with exactly two buckets. With Object.groupBy available, you can also write it as const { true: yes = [], false: no = [] } = Object.groupBy(list, test), since the boolean keys become the strings "true" and "false".

Summing, minimum and maximum

Two quick ones you will use constantly:

JavaScript
const total = cart.reduce((sum, item) => sum + item.price * item.qty, 0);

const prices = cart.map((item) => item.price);
const cheapest = Math.min(...prices);
const priciest = Math.max(...prices);

Always give reduce a starting value (0 here). Without it, an empty cart throws a TypeError. And Math.min() of an empty list is Infinity, so check for empty input first.

More recipes: sets, ranking and rearranging

The next recipes answer questions that come up constantly: what do two lists share, which items are in only one of them, what are the biggest values, and how do I move items around without mutating the original.

Common, different and unique-to-one-side

For lists of primitives, a Set makes membership checks fast. Filtering one array against a set of the other gives the intersection and the differences:

JS Common elements and differences

Press Run (or Ctrl + Enter) to see the console output here.

No output.

See Sets for union, intersection and the other built-in set methods, and their browser support.

Largest values, second largest and the best total

Sort a copy when you want the top n items: toSorted() returns a new array, while sort() would reorder the original. For only the second largest, a single pass is cheaper than sorting. Kadane's algorithm finds the best sum of consecutive items in one pass: keep the best sum ending at the current item, which either extends the previous run or starts again.

JS Top n, second largest, Kadane

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Swap, rotate and truncate

Destructuring swaps two items in one line. Rotation moves items from one end to the other; slice() plus spread builds the result without touching the original. Truncating is just setting length, or taking a slice.

JS Swap, rotate, truncate

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If the slicing in rotate is hard to read, a loop calling list.unshift(list.pop()) (right) or list.push(list.shift()) (left) k times is simpler. It mutates the array, so copy it first.

Merging sorted arrays

Merging two already-sorted arrays takes one pass with two pointers, much cheaper than concatenating and sorting again. It is also the "merge" step of merge sort (see Algorithms).

JS Merge two sorted arrays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two-dimensional arrays: CSV, sums and products

A matrix is an array of row arrays. Turning it into CSV is a map and a join, with quoting for any cell that contains a comma, a quote or a newline. Matrix sums are two nested loops; the product uses the row-by-column rule.

JS Matrices and CSV

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Removing duplicate objects

A Set cannot tell two objects with equal contents apart, because it compares by reference. Pick the field that identifies an object (an id, an email) and keep the first one per key, using a Map:

JS Dedupe objects by key

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Combining recipes

The real power of these recipes shows when you chain them. Each one takes an array (or a set, or a map) and returns a new value, so the output of one becomes the input of the next. Here is a single expression that answers "which tags appear on more than one published post, most popular first?":

JavaScript
const popularTags = Object.entries(
  Object.groupBy(
    posts.filter((p) => p.published).flatMap((p) => p.tags),
    (tag) => tag
  )
)
  .map(([tag, list]) => [tag, list.length])
  .filter(([, count]) => count > 1)
  .toSorted((a, b) => b[1] - a[1]);

When a chain grows this long, give the intermediate steps names (const publishedTags = ...). Short, well-named variables make the code easier to read and to debug in the console, and they cost nothing in speed for everyday data sizes. Reach for a single for...of loop only when you have measured a real performance problem with very large arrays.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call creates the array [1, 2, 3, 4]?

    Array.from builds 4 slots from { length: 4 } and the mapping function turns each index into i + 1.
  2. 2. What does Object.groupBy(people, (p) => p.city) return?

    Object.groupBy returns a (null-prototype) object whose keys are the values your callback returned. Map.groupBy would return a Map instead.
  3. 3. Why doesn't [...new Set(list)] remove two objects that look identical, such as two copies of { id: 1 }?

    A Set treats two separate objects as different values, even if their contents match. Deduplicate objects by a key using a Map instead.
  4. 4. What does [[1, 2], [], [3]].flatMap((x) => x) return?

    flatMap maps and then flattens one level. The empty array contributes nothing.

Summary

  • Array.from({ length: n }, (_, i) => ...) builds ranges, grids and other arrays of a given size.
  • Object.groupBy() and Map.groupBy() (ES2024) split a list into buckets by key; reduce with ??= is the fallback for older environments.
  • Count with reduce into an object or a Map.
  • [...new Set(list)] removes duplicate primitives; a Map keyed by id removes duplicate objects.
  • flat() flattens nested arrays; flatMap() maps each item to zero, one or many results.
  • Chunk with Array.from + slice, zip with an index, partition with reduce or groupBy.

Next: Sets โ€” collections of unique values and the operations that combine them.