Examples

Examples · Arrays

JavaScript Array Examples

A runnable cookbook of the array tasks you reach for every day — summing, finding, sorting, de-duplicating, grouping and more. Each links to a deeper reference or how-to.

XCODXExamples · Updated

Overview

Short, copy-paste examples for the most common things you do with arrays in JavaScript. Every snippet runs — edit any of them in the online JavaScript compiler. For the full mechanics of a method, follow the links to its reference page.

Examples

Sum and average

const nums = [10, 20, 30, 40];

const sum = nums.reduce((a, b) => a + b, 0); // 100
const avg = sum / nums.length;               // 25

See reduce() for how the accumulator works.

Largest and smallest

const nums = [3, 7, 2, 9, 4];

const max = Math.max(...nums); // 9
const min = Math.min(...nums); // 2

Unique values

const unique = [...new Set([1, 1, 2, 3, 3])]; // [1, 2, 3]

For objects and the NaN edge case, see how to remove duplicates.

Transform and filter

const nums = [1, 2, 3, 4, 5, 6];

const doubledEvens = nums
  .filter(n => n % 2 === 0) // [2, 4, 6]
  .map(n => n * 2);         // [4, 8, 12]

Deep dives: map() and filter().

Find an item

const users = [{ id: 1 }, { id: 2 }, { id: 3 }];

const user = users.find(u => u.id === 2); // { id: 2 }
const has = users.some(u => u.id === 2);  // true
const allPositive = [1, 2, 3].every(n => n > 0); // true

Sort (a copy)

const nums = [10, 1, 21, 2];

const sorted = [...nums].sort((a, b) => a - b); // [1, 2, 10, 21]

Watch the default-sort trap — see how to sort an array and sort().

Flatten nested arrays

const flat = [[1, 2], [3, 4], [5]].flat(); // [1, 2, 3, 4, 5]

Group by a key

Split into chunks

function chunk(arr, size) {
  const out = [];
  for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
  return out;
}

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

Make a range of numbers

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

Frequently asked questions

How do I sum an array of numbers?
Use reduce with an initial value of 0: array.reduce((a, b) => a + b, 0).
How do I get unique values from an array?
For primitives, [...new Set(array)]. For objects, de-duplicate by a key with a Map — see the remove-duplicates how-to.
How do I find an item in an array?
Use find() to get the first matching element, some() to test whether any match, and every() to test whether all match.