JavaScript logoJavaScriptINTERMEDIATE

JavaScript Array Methods

JavaScript array methods cheat sheet with map, filter, reduce, find, sort, and practical code examples for data transformation.

5 min read
javascriptarraysmethodses6

Sign in to mark items as known and track your progress.

Sign in

Transformation Methods

Transform arrays into new arrays with modified data

map() - Transform Elements

Create a new array by transforming each element

javascript
// Create new array by transforming each element
const doubled = [1, 2, 3].map(x => x * 2);
// [2, 4, 6]

const users = [{name: 'John', age: 30}];
const names = users.map(u => u.name);
// ['John']

// With index
const indexed = ['a', 'b'].map((val, i) => `${i}: ${val}`);
// ['0: a', '1: b']
🟢 Essential - Most commonly used array method
💡 Returns new array, doesn't modify original
⚡ Perfect for data transformation and React rendering
📌 Always returns array of same length as original
🔗 Related: forEach (for side effects), filter (for selection)

filter() - Select Elements

Create a new array with elements that pass a test

javascript
// Keep elements that pass the test
const evens = [1, 2, 3, 4].filter(x => x % 2 === 0);
// [2, 4]

const adults = users.filter(u => u.age >= 18);

// Remove falsy values
const truthy = [0, 1, '', 'hello', null].filter(Boolean);
// [1, 'hello']
🟢 Essential - Use for selecting subset of elements
💡 Returns new array with filtered items
⚡ Chainable with other array methods
📌 Original array remains unchanged
⚠️ Returns empty array if nothing matches

reduce() - Aggregate Values

Reduce array to single value using accumulator

javascript
// Sum all numbers
const sum = [1, 2, 3].reduce((acc, x) => acc + x, 0);
// 6

// Group by property
const grouped = items.reduce((acc, item) => {
  acc[item.category] = acc[item.category] || [];
  acc[item.category].push(item);
  return acc;
}, {});
🔴 Advanced - Powerful but complex method
💡 Can return any type: number, string, object, array
⚡ Use for sums, counts, grouping, flattening
⚠️ Always provide initial value to avoid errors
📌 Accumulator carries value between iterations

Searching & Testing

Find elements and test array conditions

find() & findIndex()

Find first element matching condition or its index

javascript
// Find first matching element
const found = [1, 2, 3].find(x => x > 1);
// 2

// Find index of first match
const index = [1, 2, 3].findIndex(x => x > 1);
// 1

// Find in objects
const user = users.find(u => u.id === 123);
const userIndex = users.findIndex(u => u.id === 123);
🟢 Essential - Better than filter()[0] for single item
💡 find() returns element, findIndex() returns index
⚡ Stops searching after first match (efficient)
⚠️ Returns undefined/-1 if nothing found
📌 Use findLast() for searching from end (ES2023)

some() & every()

Test if any/all elements pass a condition

javascript
// Test if ANY element passes
const hasEven = [1, 2, 3].some(x => x % 2 === 0);
// true

// Test if ALL elements pass
const allPositive = [1, 2, 3].every(x => x > 0);
// true

// Check for empty array
const isEmpty = array.length === 0 || array.every(x => !x);
💡 Returns boolean, not array elements
⚡ some() stops at first true (OR logic)
⚡ every() stops at first false (AND logic)
📌 Empty array: some() returns false, every() returns true
🔗 Related: includes() for simple value checking

includes() & indexOf()

Check if array contains a value or find its position

javascript
// Check if array contains value
[1, 2, 3].includes(2); // true
['a', 'b'].includes('c'); // false

// Find index of value
[1, 2, 3].indexOf(2); // 1
['a', 'b'].indexOf('c'); // -1

// Starting from index
arr.includes(value, fromIndex);
arr.indexOf(value, fromIndex);
🟢 Essential - Simple value checking
💡 includes() returns boolean, indexOf() returns position
⚡ Use includes() for existence check (cleaner)
⚠️ Uses strict equality (===) for comparison
📌 indexOf() returns -1 if not found

Array Manipulation

Add, remove, and rearrange array elements

Adding & Removing Elements

Methods to add and remove array elements

javascript
// Add/remove from end
arr.push(4, 5);    // Returns new length
arr.pop();         // Returns removed element

// Add/remove from start
arr.unshift(0);    // Returns new length
arr.shift();       // Returns removed element

// Add/remove anywhere
arr.splice(1, 2, 'a', 'b'); // At index 1, remove 2, add 'a', 'b'
🟢 Essential - Core array operations
⚠️ push/pop/shift/unshift MUTATE the array
💡 push/pop work on end (fast), shift/unshift on start (slower)
⚡ Use spread [...arr, item] for immutable operations
📌 All mutating methods return different values

slice() & concat()

Extract portions and combine arrays without mutation

javascript
// Copy portion of array
const portion = arr.slice(1, 3); // Items at index 1, 2
const last3 = arr.slice(-3);     // Last 3 items
const copy = arr.slice();        // Full copy

// Combine arrays
const combined = arr1.concat(arr2, arr3);
const combined = [...arr1, ...arr2]; // Modern way
🟢 Essential - Safe array operations
💡 slice() extracts portion, concat() combines arrays
⚡ Both return new arrays (immutable)
📌 Negative indices count from end
🔗 Use spread [...arr1, ...arr2] as modern concat

sort() & reverse()

Sort and reverse array elements in place

javascript
// Sort (mutates array!)
arr.sort(); // Alphabetical
arr.sort((a, b) => a - b); // Numeric ascending
arr.sort((a, b) => b - a); // Numeric descending

// Reverse (mutates array!)
arr.reverse();

// Non-mutating versions
const sorted = [...arr].sort();
const reversed = [...arr].reverse();
⚠️ Both MUTATE the original array
💡 Use [...arr].sort() to avoid mutation
🔴 sort() converts to strings by default (10 < 2)
📌 Provide compare function for numbers: (a, b) => a - b
⚡ toSorted() and toReversed() are immutable (ES2023)

Iteration Methods

Loop through arrays and process elements

forEach() - Side Effects

Execute function for each element (side effects only)

javascript
// Execute function for each element (no return)
[1, 2, 3].forEach(x => console.log(x));

// With index and array
arr.forEach((val, index, array) => {
  console.log(`${index}: ${val}`);
});

// Can't break early (use for...of instead)
💡 Use for side effects (logging, DOM updates)
⚠️ Cannot break/return early like for loop
📌 Returns undefined, not chainable
🔗 Use map() if you need transformed array
⚡ Skips empty slots in sparse arrays

join() & Array/String Conversion

Convert array to string and vice versa

javascript
// Array to string
[1, 2, 3].join();      // '1,2,3'
[1, 2, 3].join(' - '); // '1 - 2 - 3'
[1, 2, 3].join('');    // '123'

// String to array
'1,2,3'.split(',');    // ['1', '2', '3']
'hello'.split('');     // ['h', 'e', 'l', 'l', 'o']
Array.from('hello');   // ['h', 'e', 'l', 'l', 'o']
🟢 Essential - Common for display and parsing
💡 join() array→string, split() string→array
📌 Default separator is comma for join()
⚡ Use template literals for complex formatting
🔗 Related: toString() for simple conversion

flat() & flatMap()

Flatten nested arrays and map-then-flatten

javascript
// Flatten nested arrays
[1, [2, 3]].flat();        // [1, 2, 3]
[1, [2, [3]]].flat(2);     // [1, 2, 3] (depth 2)

// Map and flatten
[1, 2].flatMap(x => [x, x * 2]); // [1, 2, 2, 4]

// Remove empty slots
[1, , 3].flat(); // [1, 3]
💡 flat() removes nesting levels (default: 1)
⚡ flatMap() = map() + flat(1) in one pass
📌 Use Infinity to flatten all levels
🔗 Great for handling nested data structures
⚠️ Removes empty slots from arrays

Array Creation & Conversion

Create new arrays and convert between types

Array.from() & Array.of()

Create arrays from array-like objects or iterables

javascript
// Create array from iterable
Array.from('hello');           // ['h', 'e', 'l', 'l', 'o']
Array.from(new Set([1, 2]));   // [1, 2]

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

// Create array from arguments
Array.of(1, 2, 3);    // [1, 2, 3]
Array.of(7);          // [7] (not empty array of length 7)
💡 Array.from() converts iterables to arrays
⚡ Second parameter maps elements during creation
📌 Array.of() creates array from arguments
🔗 Useful for NodeList, arguments, Set, Map
🟢 Essential for DOM manipulation

fill() & copyWithin()

Fill array with values or copy elements within

javascript
// Fill array with value
[1, 2, 3].fill(0);        // [0, 0, 0]
[1, 2, 3].fill(0, 1);     // [1, 0, 0]
[1, 2, 3].fill(0, 1, 2);  // [1, 0, 3]

// Copy within array
[1, 2, 3, 4, 5].copyWithin(0, 3); // [4, 5, 3, 4, 5]
⚠️ Both methods MUTATE the array
💡 fill() sets multiple elements to same value
📌 copyWithin() copies part to another position
⚡ Useful for array initialization
🔴 Be careful with object references in fill()

Modern Array Methods (ES2023+)

Immutable variants, findLast, fromAsync, and grouping (ES2023+)

Immutable Variants: toSorted, toReversed, toSpliced, with

Non-mutating versions of sort/reverse/splice and indexed update

javascript
const nums = [3, 1, 2]

const sorted = nums.toSorted()        // [1, 2, 3]   — nums untouched
const reversed = nums.toReversed()    // [2, 1, 3]   — nums untouched
const removed = nums.toSpliced(0, 1)  // [1, 2]      — nums untouched
const updated = nums.with(0, 99)      // [99, 1, 2]  — nums untouched

console.log(nums)                     // [3, 1, 2]   — original preserved
💡 Same shape as sort/reverse/splice — just prefixed with `to` (and `with` for indexed set)
📌 Always returns a new array — safe for React/Redux state, signals, etc.
⚡ Replaces the [...arr].sort() / structuredClone copy-then-mutate idiom
🎯 `with(-1, x)` is the cleanest way to "replace the last element"
es2023immutablemodern

findLast & findLastIndex

Search from the end — perfect for "most recent matching"

javascript
const events = [
  { type: 'login', at: 1 },
  { type: 'click', at: 2 },
  { type: 'login', at: 3 },
  { type: 'logout', at: 4 },
]

const lastLogin = events.findLast(e => e.type === 'login')
// { type: 'login', at: 3 }

const lastLoginIdx = events.findLastIndex(e => e.type === 'login')
// 2
💡 Iterates from the end — early-returns on first match like find()
⚡ Way cheaper than `[...arr].reverse().find(...)` on large arrays
📌 findLastIndex returns -1 on no match — same convention as findIndex
🎯 Pair with `with()` for "update the most recent matching item"
es2023search

Array.fromAsync & Grouping

Build arrays from async iterables, group by key (Object.groupBy / Map.groupBy)

javascript
// Array.fromAsync — collect an async iterable into an array
async function* lines(file) {
  for await (const chunk of file.stream()) yield chunk
}
const allLines = await Array.fromAsync(lines(myFile))

// Object.groupBy — group items by a derived key (ES2024)
const items = [
  { name: 'apple', type: 'fruit' },
  { name: 'carrot', type: 'veg' },
  { name: 'pear', type: 'fruit' },
]
const byType = Object.groupBy(items, x => x.type)
// { fruit: [{...apple}, {...pear}], veg: [{...carrot}] }

// Map.groupBy — same idea, but the key can be any value (incl. objects)
const byParent = Map.groupBy(rows, r => r.parent)
💡 Array.fromAsync replaces the manual `for await ... push` loop
⚡ Object.groupBy returns a null-prototype object — no .hasOwnProperty needed
📌 Map.groupBy is the version to use when keys are objects, not strings
🎯 Pair fromAsync with fetch + ReadableStream for clean streaming-to-array code
es2024asyncgrouping