Syntax Cache
BlogMethodFeaturesHow It WorksBuild a Game
  1. Home
  2. Cheat Sheets
  3. JavaScript
  4. JavaScript Array Methods Cheat Sheet
JavaScriptCheat Sheet

JavaScript Array Methods Cheat Sheet

Quick-reference for every array method you actually use. Each section includes copy-ready snippets with inline output comments.

On this page
  1. 1Creating Arrays
  2. 2Transform: map, filter, reduce
  3. 3Find: find, findIndex, includes, indexOf
  4. 4Test: some, every
  5. 5Flatten: flat, flatMap
  6. 6Sorting
  7. 7Extract and Modify: slice, splice
  8. 8Iteration: forEach vs for...of
  9. 9Spread and Destructuring
  10. 10Add and Remove: push, pop, shift, unshift
  11. 11Modern Methods: at, with, groupBy
  12. 12Chaining Patterns
Creating ArraysTransform: map, filter, reduceFind: find, findIndex, includes, indexOfTest: some, everyFlatten: flat, flatMapSortingExtract and Modify: slice, spliceIteration: forEach vs for...ofSpread and DestructuringAdd and Remove: push, pop, shift, unshiftModern Methods: at, with, groupByChaining Patterns

Creating Arrays

JavaScript arrays are ordered, zero-indexed, and can hold mixed types. Use literals, Array.from(), or spread for creation.

Array literals
const nums = [1, 2, 3];
const mixed = [1, 'two', true, null];
const empty = [];
Array.from() with iterables and mapping
Array.from('hello')           // => ['h', 'e', 'l', 'l', 'o']
Array.from({ length: 5 }, (_, i) => i)  // => [0, 1, 2, 3, 4]
Array.from(new Set([1, 2, 2, 3]))       // => [1, 2, 3]
Array.of() vs Array()
Array.of(5)    // => [5]        (one element: 5)
Array(5)       // => [, , , , ,] (five empty slots)
Array.of(1, 2) // => [1, 2]

Array(n) creates sparse slots, not undefined values. Use Array.from({ length: n }) for filled arrays.

Spread to copy or merge
const copy = [...nums];              // => [1, 2, 3]
const merged = [...[1, 2], ...[3, 4]] // => [1, 2, 3, 4]

Transform: map, filter, reduce

The big three. map transforms each element, filter selects elements, reduce accumulates into a single value.

map() — transform each element
[1, 2, 3].map(x => x * 2)        // => [2, 4, 6]
['hello', 'world'].map(s => s.toUpperCase())
// => ['HELLO', 'WORLD']
filter() — keep matching elements
[1, 2, 3, 4, 5].filter(x => x % 2 === 0)  // => [2, 4]
['', 'hi', '', 'bye'].filter(Boolean)       // => ['hi', 'bye']
reduce() — accumulate to one value
[1, 2, 3, 4].reduce((sum, x) => sum + x, 0)  // => 10

// Group by property
const items = [{ type: 'a' }, { type: 'b' }, { type: 'a' }];
items.reduce((acc, item) => {
  (acc[item.type] ??= []).push(item);
  return acc;
}, {})
// => { a: [{type:'a'},{type:'a'}], b: [{type:'b'}] }
Chain map + filter
const prices = [10, 25, 5, 50, 15];
prices
  .filter(p => p >= 10)
  .map(p => `$${p.toFixed(2)}`)
// => ['$10.00', '$25.00', '$50.00', '$15.00']

Find: find, findIndex, includes, indexOf

Search for elements by value or predicate. find/findIndex take callbacks; includes/indexOf check exact values.

find() — first match or undefined
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
users.find(u => u.id === 2)       // => { id: 2, name: 'Bob' }
users.find(u => u.id === 99)      // => undefined
findIndex() — index or -1
[10, 20, 30].findIndex(x => x > 15)  // => 1
[10, 20, 30].findIndex(x => x > 50)  // => -1
includes() — boolean check
[1, 2, 3].includes(2)   // => true
[1, 2, 3].includes(5)   // => false

includes() uses strict equality (===). It cannot find objects by property — use find() for that.

indexOf() — position or -1
['a', 'b', 'c', 'b'].indexOf('b')      // => 1
['a', 'b', 'c', 'b'].lastIndexOf('b')  // => 3

Test: some, every

Boolean tests across arrays. some() short-circuits on first true; every() short-circuits on first false.

some() — at least one passes
[1, 2, 3].some(x => x > 2)   // => true
[1, 2, 3].some(x => x > 5)   // => false
every() — all must pass
[2, 4, 6].every(x => x % 2 === 0)  // => true
[2, 4, 5].every(x => x % 2 === 0)  // => false
Validate form fields
const fields = ['name', 'email', 'phone'];
const values = { name: 'Alice', email: 'a@b.com', phone: '' };
fields.every(f => values[f]?.trim())  // => false (phone is empty)

Flatten: flat, flatMap

flat() removes nesting to a given depth. flatMap() maps then flattens one level — useful for one-to-many transformations.

flat() — flatten nested arrays
[1, [2, 3], [4, [5]]].flat()     // => [1, 2, 3, 4, [5]]
[1, [2, [3, [4]]]].flat(Infinity) // => [1, 2, 3, 4]
flatMap() — map then flatten one level
['hello world', 'goodbye'].flatMap(s => s.split(' '))
// => ['hello', 'world', 'goodbye']

// Filter and transform in one pass
[1, 2, 3].flatMap(x => x % 2 ? [x * 10] : [])
// => [10, 30]  (even numbers dropped)
flatMap vs map + flat
// These are equivalent:
arr.flatMap(fn)
arr.map(fn).flat()
// flatMap is more efficient (single pass)

Sorting

sort() mutates the original array and converts elements to strings by default. Always pass a compare function for numbers.

String sort (default)
['banana', 'apple', 'cherry'].sort()
// => ['apple', 'banana', 'cherry']
Numeric sort (compare function required)
[10, 1, 21, 2].sort()              // => [1, 10, 2, 21] (string order!)
[10, 1, 21, 2].sort((a, b) => a - b)  // => [1, 2, 10, 21]
[10, 1, 21, 2].sort((a, b) => b - a)  // => [21, 10, 2, 1]

Without a compare function, sort converts to strings: "10" < "2" because "1" < "2". Always pass (a, b) => a - b for numbers.

Sort objects by property
const users = [
  { name: 'Charlie', age: 25 },
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 20 },
];
users.sort((a, b) => a.age - b.age);
// => [{ name: 'Bob', age: 20 }, ...]
toSorted() — non-mutating (ES2023)
const nums = [3, 1, 2];
const sorted = nums.toSorted((a, b) => a - b);
sorted  // => [1, 2, 3]
nums    // => [3, 1, 2] (unchanged)

Extract and Modify: slice, splice

slice() copies a portion without mutating. splice() inserts, removes, or replaces elements in place.

slice() — extract without mutating
const arr = [0, 1, 2, 3, 4];
arr.slice(1, 3)   // => [1, 2]
arr.slice(-2)     // => [3, 4]
arr.slice()       // => [0, 1, 2, 3, 4] (shallow copy)
splice() — remove elements
const arr = ['a', 'b', 'c', 'd'];
const removed = arr.splice(1, 2);
removed  // => ['b', 'c']
arr      // => ['a', 'd']
splice() — insert elements
const arr = ['a', 'd'];
arr.splice(1, 0, 'b', 'c');
arr  // => ['a', 'b', 'c', 'd']
toSpliced() — non-mutating (ES2023)
const arr = [1, 2, 3, 4];
const result = arr.toSpliced(1, 2, 'a', 'b');
result  // => [1, 'a', 'b', 4]
arr     // => [1, 2, 3, 4] (unchanged)

Iteration: forEach vs for...of

forEach runs a callback per element. for...of supports break, continue, and await. Choose based on control flow needs.

forEach() — callback per element
['a', 'b', 'c'].forEach((item, index) => {
  console.log(`${index}: ${item}`);
});
// 0: a
// 1: b
// 2: c
for...of — supports break and continue
for (const item of ['a', 'b', 'c', 'd']) {
  if (item === 'c') break;
  console.log(item);
}
// a
// b
for...of with entries() for index
for (const [i, val] of ['a', 'b', 'c'].entries()) {
  console.log(`${i}: ${val}`);
}

Use for...of when you need break, continue, or await. Use forEach for simple side effects without control flow.

Spread and Destructuring

Spread copies arrays and merges them. Destructuring extracts elements into variables. Both are essential modern JS patterns.

Spread: copy, merge, push
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b];          // => [1, 2, 3, 4]
const withNew = [...a, 5];            // => [1, 2, 5]
const copy = [...a];                  // => [1, 2] (shallow)
Destructuring: extract elements
const [first, second, ...rest] = [1, 2, 3, 4, 5];
first   // => 1
second  // => 2
rest    // => [3, 4, 5]
Skip elements and defaults
const [, , third] = ['a', 'b', 'c'];
third  // => 'c'

const [x = 0, y = 0] = [42];
x  // => 42
y  // => 0 (default)
Swap variables
let a = 1, b = 2;
[a, b] = [b, a];
a  // => 2
b  // => 1

Add and Remove: push, pop, shift, unshift

Stack and queue operations. push/pop work at the end; shift/unshift at the start. All mutate the array.

push() and pop() — end of array
const arr = [1, 2];
arr.push(3);       // arr => [1, 2, 3], returns 3 (new length)
arr.pop();         // arr => [1, 2], returns 3 (removed)
unshift() and shift() — start of array
const arr = [2, 3];
arr.unshift(1);    // arr => [1, 2, 3], returns 3 (new length)
arr.shift();       // arr => [2, 3], returns 1 (removed)
Non-mutating alternatives with spread
const arr = [1, 2, 3];
const added = [...arr, 4];       // => [1, 2, 3, 4]
const prepended = [0, ...arr];   // => [0, 1, 2, 3]
const removed = arr.slice(0, -1); // => [1, 2] (remove last)

In React and other immutable-state patterns, prefer spread or toSpliced() over push/splice.

Modern Methods: at, with, groupBy

ES2022+ additions for cleaner code. at() supports negative indexing; with() returns a copy with one element changed.

at() — negative indexing
const arr = ['a', 'b', 'c', 'd'];
arr.at(0)    // => 'a'
arr.at(-1)   // => 'd' (last)
arr.at(-2)   // => 'c'
with() — non-mutating set (ES2023)
const arr = [1, 2, 3];
const updated = arr.with(1, 20);
updated  // => [1, 20, 3]
arr      // => [1, 2, 3] (unchanged)
Object.groupBy() (ES2024)
const items = [
  { name: 'apple', type: 'fruit' },
  { name: 'carrot', type: 'veggie' },
  { name: 'banana', type: 'fruit' },
];
Object.groupBy(items, item => item.type);
// => { fruit: [apple, banana], veggie: [carrot] }

Object.groupBy is a static method, not an array method. It returns a null-prototype object.

Chaining Patterns

Method chaining is idiomatic JavaScript. Chain map, filter, sort, and reduce to build pipelines.

Pipeline: filter + map + sort
const products = [
  { name: 'Widget', price: 25, inStock: true },
  { name: 'Gadget', price: 50, inStock: false },
  { name: 'Doohickey', price: 10, inStock: true },
];

products
  .filter(p => p.inStock)
  .map(p => ({ ...p, display: `${p.name}: $${p.price}` }))
  .sort((a, b) => a.price - b.price);
// => [{ name: 'Doohickey', ... }, { name: 'Widget', ... }]
Unique values via Set
const ids = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(ids)];  // => [1, 2, 3]
Sum with reduce
const total = [10, 20, 30].reduce((sum, n) => sum + n, 0);
total  // => 60
Max / min without Math spread
const nums = [5, 2, 9, 1, 7];
Math.max(...nums)  // => 9
Math.min(...nums)  // => 1

For very large arrays (>100k), Math.max(...arr) can hit the call stack limit. Use reduce instead.

Learn JavaScript in Depth
JavaScript Loops Practice →JavaScript Functions Practice →JavaScript String Methods Practice →
Warm-up1 / 2

Can you write this from memory?

Create an empty Map called `cache`.

See Also
Object Methods →ES6+ Features →String Methods →

Start Practicing JavaScript

Free daily exercises with spaced repetition. No credit card required.

← Back to JavaScript Syntax Practice
Syntax Cache

Build syntax muscle memory with spaced repetition.

Product

  • Pricing
  • Our Method
  • Daily Practice
  • Design Patterns
  • Interview Prep

Resources

  • Blog
  • Compare
  • Cheat Sheets
  • Vibe Coding
  • Muscle Memory

Languages

  • Python
  • JavaScript
  • TypeScript
  • Rust
  • SQL
  • GDScript

Legal

  • Terms
  • Privacy
  • Contact

© 2026 Syntax Cache

Cancel anytime in 2 clicks. Keep access until the end of your billing period.

No refunds for partial billing periods.