Array Methods

Essential Array Methods

JavaScript provides many built-in methods for array manipulation, creation, and transformation.

Try Array Methods

Code Editor
Console Output
Click "Run" to execute your code...

Example 1: Adding/Removing Elements

const arr = [1, 2, 3];

// push() - add to end, returns new length
const length = arr.push(4, 5);
console.log(arr);    // [1, 2, 3, 4, 5]
console.log(length); // 5

// pop() - remove from end, returns removed element
const last = arr.pop();
console.log(arr);  // [1, 2, 3, 4]
console.log(last); // 5

// unshift() - add to beginning, returns new length
arr.unshift(0);
console.log(arr); // [0, 1, 2, 3, 4]

// shift() - remove from beginning, returns removed element
const first = arr.shift();
console.log(arr);   // [1, 2, 3, 4]
console.log(first); // 0

// splice() - add/remove at any position
const numbers = [1, 2, 3, 4, 5];

// Remove 2 elements starting at index 2
const removed = numbers.splice(2, 2);
console.log(numbers); // [1, 2, 5]
console.log(removed); // [3, 4]

// Insert elements
numbers.splice(2, 0, 3, 4); // At index 2, remove 0, insert 3, 4
console.log(numbers); // [1, 2, 3, 4, 5]

// Replace elements
numbers.splice(1, 2, 10, 20); // At index 1, remove 2, insert 10, 20
console.log(numbers); // [1, 10, 20, 4, 5]

Example 2: Searching and Finding

const fruits = ['apple', 'banana', 'orange', 'banana', 'grape'];

// indexOf() - first index of element, -1 if not found
console.log(fruits.indexOf('banana'));    // 1
console.log(fruits.indexOf('mango'));     // -1
console.log(fruits.indexOf('banana', 2)); // 3 (start from index 2)

// lastIndexOf() - last index of element
console.log(fruits.lastIndexOf('banana')); // 3

// includes() - checks if array contains element
console.log(fruits.includes('orange')); // true
console.log(fruits.includes('mango'));  // false

// find() - returns first element that matches
const numbers = [1, 5, 10, 15, 20];
const found = numbers.find(num => num > 10);
console.log(found); // 15

// findIndex() - returns index of first match
const index = numbers.findIndex(num => num > 10);
console.log(index); // 3

// findLast() - returns last element that matches (ES2023)
const lastFound = numbers.findLast(num => num > 5);
console.log(lastFound); // 20

// findLastIndex() - returns index of last match (ES2023)
const lastIndex = numbers.findLastIndex(num => num > 5);
console.log(lastIndex); // 4

Example 3: Transforming Arrays

// slice() - returns shallow copy of portion
const arr = [1, 2, 3, 4, 5];
const sliced = arr.slice(1, 4); // From index 1 to 4 (not including 4)
console.log(sliced); // [2, 3, 4]
console.log(arr);    // [1, 2, 3, 4, 5] (unchanged)

// Negative indices
console.log(arr.slice(-3));    // [3, 4, 5] (last 3)
console.log(arr.slice(1, -1)); // [2, 3, 4]

// concat() - merge arrays
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];
const merged = arr1.concat(arr2, arr3);
console.log(merged); // [1, 2, 3, 4, 5, 6]

// Modern alternative: spread operator
const merged2 = [...arr1, ...arr2, ...arr3];
console.log(merged2); // [1, 2, 3, 4, 5, 6]

// join() - converts array to string
const words = ['Hello', 'World', 'JavaScript'];
console.log(words.join(' '));  // 'Hello World JavaScript'
console.log(words.join('-'));  // 'Hello-World-JavaScript'
console.log(words.join(''));   // 'HelloWorldJavaScript'

// reverse() - reverses array in place
const nums = [1, 2, 3, 4, 5];
nums.reverse();
console.log(nums); // [5, 4, 3, 2, 1]

// Non-mutating reverse
const original = [1, 2, 3, 4, 5];
const reversed = [...original].reverse();
console.log(reversed); // [5, 4, 3, 2, 1]
console.log(original); // [1, 2, 3, 4, 5] (unchanged)

// flat() - flattens nested arrays
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat());    // [1, 2, 3, 4, [5, 6]] (1 level)
console.log(nested.flat(2));   // [1, 2, 3, 4, 5, 6] (2 levels)
console.log(nested.flat(Infinity)); // Flatten all levels

// flatMap() - map then flat (1 level)
const sentences = ['Hello world', 'How are you'];
const words2 = sentences.flatMap(s => s.split(' '));
console.log(words2); // ['Hello', 'world', 'How', 'are', 'you']

Example 4: Sorting Arrays

// sort() - sorts array in place (mutates)
const fruits = ['banana', 'apple', 'orange', 'grape'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'grape', 'orange']

// Numbers (default sort is alphabetical!)
const numbers = [10, 5, 40, 25, 100, 1];
numbers.sort();
console.log(numbers); // [1, 10, 100, 25, 40, 5] (wrong!)

// Correct number sorting
numbers.sort((a, b) => a - b); // Ascending
console.log(numbers); // [1, 5, 10, 25, 40, 100]

numbers.sort((a, b) => b - a); // Descending
console.log(numbers); // [100, 40, 25, 10, 5, 1]

// Sorting objects
const users = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 },
  { name: 'Bob', age: 35 }
];

// Sort by age
users.sort((a, b) => a.age - b.age);
console.log(users);
// [{ name: 'Jane', age: 25 }, { name: 'John', age: 30 }, { name: 'Bob', age: 35 }]

// Sort by name
users.sort((a, b) => a.name.localeCompare(b.name));
console.log(users);

// toSorted() - returns new sorted array, doesn't mutate (ES2023)
const original = [3, 1, 4, 1, 5];
const sorted = original.toSorted((a, b) => a - b);
console.log(sorted);   // [1, 1, 3, 4, 5]
console.log(original); // [3, 1, 4, 1, 5] (unchanged)

// toReversed() - non-mutating reverse (ES2023)
const reversed = original.toReversed();
console.log(reversed); // [5, 1, 4, 1, 3]
console.log(original); // [3, 1, 4, 1, 5] (unchanged)

Example 5: Other Useful Methods

// fill() - fill array with static value
const arr1 = [1, 2, 3, 4, 5];
arr1.fill(0);
console.log(arr1); // [0, 0, 0, 0, 0]

const arr2 = [1, 2, 3, 4, 5];
arr2.fill(9, 2, 4); // Fill with 9 from index 2 to 4
console.log(arr2); // [1, 2, 9, 9, 5]

// Array.from() - create array from iterable
console.log(Array.from('hello')); // ['h', 'e', 'l', 'l', 'o']
console.log(Array.from([1, 2, 3], x => x * 2)); // [2, 4, 6]

// Create array with sequence
const range = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(range); // [1, 2, 3, 4, 5]

// Array.of() - create array from arguments
console.log(Array.of(1, 2, 3)); // [1, 2, 3]
console.log(Array.of(7));       // [7] (not array with 7 empty slots)
console.log(new Array(7));      // [empty × 7]

// copyWithin() - copy part of array to another location
const arr3 = [1, 2, 3, 4, 5];
arr3.copyWithin(0, 3); // Copy from index 3 to index 0
console.log(arr3); // [4, 5, 3, 4, 5]

// entries() - returns iterator of [index, value] pairs
const fruits = ['apple', 'banana', 'orange'];
for (const [index, fruit] of fruits.entries()) {
  console.log(`${index}: ${fruit}`);
}

// keys() - returns iterator of indices
for (const index of fruits.keys()) {
  console.log(index); // 0, 1, 2
}

// values() - returns iterator of values
for (const fruit of fruits.values()) {
  console.log(fruit); // apple, banana, orange
}

// at() - get element at index (supports negative)
const items = ['a', 'b', 'c', 'd', 'e'];
console.log(items.at(0));   // 'a'
console.log(items.at(-1));  // 'e' (last element)
console.log(items.at(-2));  // 'd' (second to last)

// with() - returns new array with element replaced (ES2023)
const nums = [1, 2, 3, 4, 5];
const newNums = nums.with(2, 99); // Replace index 2 with 99
console.log(newNums); // [1, 2, 99, 4, 5]
console.log(nums);    // [1, 2, 3, 4, 5] (unchanged)

Key Points

  • Mutating: push, pop, shift, unshift, splice, reverse, sort, fill
  • Non-mutating: slice, concat, map, filter, reduce, flat, flatMap
  • ES2023 adds non-mutating versions: toSorted, toReversed, with
  • Use spread operator [...] to create copies before mutating
  • indexOf/includes for simple searches, find/findIndex for complex
  • sort() requires compare function for numbers
  • Modern methods like at() support negative indices