Array Methods

Learn about JavaScript array methods with clear examples that help you add, remove, update, and manipulate arrays step-by-step.

Loading...
Array Methods

In JavaScript, arrays are mutable, which means you can change their elements after the array is created. You can update, add, or remove items without creating a new array.

JavaScript provides many built-in methods to help you work with arrays efficiently.

pop()

The pop() method removes the last element of the array and returns the removed element.

It updates the original array.

Example:

const arr = [1, 9, 13, 7];
const removedElement = arr.pop();
 
console.log(removedElement); // Output: 7
console.log(arr); // Output:  [1, 9, 13]

push()

The push() method adds a new element at the end of the array and returns the new array length.

It modifies the original array.

Example:

const arr = [1, 9, 13, 7];
const newElement = arr.push(2);
 
console.log(arr); // Output:  [1, 9, 13, 7, 2]
console.log(newElement); // Output: 5 (new array length)

shift()

The shift() method removes the first element of the array and returns the removed element.

It modifies the original array.

Example:

const arr = [1, 9, 13, 7];
const removedElement = arr.shift();
 
console.log(arr); // Output:  [9, 13, 7]
console.log(removedElement); // Output:  1

unshift()

The unshift() method adds a new element at the beginning of the array and returns the new array length.

It modifies the original array.

Example:

const arr = [1, 9, 13, 7];
const newElement = arr.unshift(2);
 
console.log(arr); // Output: [2, 1, 9, 13, 7]
console.log(newElement); // Output: 5 (new array length)

splice()

The splice() method is used to add, remove, or replace elements at any position within an array.

Syntax:

array.splice(position to add or remove element, number of elements to remove, elements to be added)

Example: 1

const arr1 = [1, 8, 13, 4, 15];
arr1.splice(2, 1); // Removes 1 element at index 2
console.log(arr1); // Output: [1, 8, 4, 15]

Here, the element 13 at index 2 is removed.

Example: 2

const arr2 = [1, 78, 13, 54, 15];
arr2.splice(1, 0, 6, 7); // Adds 6 and 7 at index 1
console.log(arr2); // Output: [1, 6, 7, 78, 13, 54, 15]

Here, no elements are removed (0), and 6 and 7 are added at index 1.

You can add as many elements as you want.


copyWithin()

The copyWithin() method copies some elements from one part of the array to another part, replacing the elements there. It does not add or remove items, the array length remains the same.

It modifies the original array.

Syntax:

array.copyWithin(target, start, end);
  • target: The index to start placing the copied elements.
  • start: The index to start copying from.
  • end (optional): The index to stop copying (not included). If omitted, it copies until the end of the array.

Example:

const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3, 5);
 
console.log(arr); // Output: [4, 5, 3, 4, 5]

Here,

  • target is 0, start is 3, and end is 5.
  • So, it copies elements from index 3 up to (but not including) index 5, that means elements [4, 5].
  • These elements [4, 5] are copied starting at index 0, replacing the elements at index 0 and 1.
  • The resulting array becomes [4, 5, 3, 4, 5].

fill()

The fill() method changes all or some elements of an array to a static value.

It modifies the original array.

Syntax:

array.fill(value, start, end);
  • value: The value to fill the array with.
  • start (optional): The starting index to begin filling (default is 0).
  • end (optional): The index to stop filling (not included, default is array length).

Example:

const arr = [1, 2, 3, 4];
arr.fill(0, 1, 3);
 
console.log(arr); // Output: [1, 0, 0, 4]

Here,

  • value is 0, start is 1, and end is 3 (but not including index 3).
  • So,
    • arr[1] becomes 0
    • arr[2] becomes 0
    • arr[3] is not changed
  • The resulting array becomes [1, 0, 0, 4].

toSpliced()

The toSpliced() method returns a new array with elements removed and/or added, similar to splice(), but it does not modify the original array.

Syntax:

array.toSpliced(position to add or remove element, number of elements to remove, elements to be added)

Example:

const arr = [1, 2, 3, 4];
const splicedArr = arr.toSpliced(1, 2, 9, 8);
 
console.log(splicedArr); // Output: [1, 9, 8, 4]
console.log(arr); // Output: [1, 2, 3, 4]

Here,

  • arr.toSpliced(1, 2, 9, 8): Start at index 1, remove 2 items, add 9 and 8.
  • Items 2 and 3 are removed, and 9 and 8 are added at index 1.
  • So the original array is still [1, 2, 3, 4] and new array is [1, 9, 8, 4].
  • The original array remains unchanged.

with()

The with() method returns a new array with the element at the specified index replaced by a new value.

The original array remains unchanged.

Syntax:

array.with(index, value);
  • index: The index (position) of the item to change.
  • value: The new value.

Example:

const arr = [1, 2, 3];
const newArr = arr.with(1, 99);
 
console.log(newArr); // Output: [1, 99, 3]
console.log(arr); // Output: [1, 2, 3]

Here,

  • The value at index 1 is replaced by 99.
  • The original array is still [1, 2, 3] and new array is [1, 99, 3].
  • The original array remains unchanged.

delete

Elements of an array can be deleted using the delete operator.

The delete operator leaves undefined holes in the array.

Example:

const arr = [1, 9, 13, 7];
delete arr[3];
 
console.log(arr); // Output: [1, 9, 13, empty]
console.log(arr[3]); // Output: undefined

Here, the element at index 3 is deleted.

Note: delete removes the element but leaves an empty spot


indexOf()

The indexOf() method searches for an element of an array and returns the position of the element.

Example:

const arr = ["red", "orange", "blue", "green", "white"];
console.log(arr.indexOf("blue")); // Output: 2
console.log(arr.indexOf("orange")); // Output: 1

lastIndexOf()

The lastIndexOf() method returns the last index of a given element in the array, or -1 if it is not present.

Example:

const arr = ["apple", "banana", "orange", "banana"];
const lastBanana = arr.lastIndexOf("banana");
 
console.log(lastBanana); // Output: 3
 
const lastPlum = arr.lastIndexOf("plum");
console.log(lastPlum); // Output: -1

includes()

The includes() method checks whether an element is present in the array or not.

Example:

const arr = [1, 3, 13, 5, 2, 6];
console.log(arr.includes(5)); // Output: true
console.log(arr.includes(7)); // Output: false

find()

The find() method returns the first value of an element based on a condition.

Syntax:

array.find(callback);
  • The callback function runs for each element.
  • It stops and returns the first element for which the callback returns true.
  • If no element satisfies the condition, it returns undefined.

Example: 1

const arr = [1, 2, 3, 4, 5, 6];
const evenNumber = arr.find((num) => num % 2 === 0);
console.log(evenNumber); // Output: 2

Here,

  • It checks each number to see if it’s even.
  • The first even number is 2, so find() returns 2.

Example: 2

const arr2 = [4, 3, 6];
const evenNumber2 = arr2.find((num) => num % 2 === 0);
console.log(evenNumber2); // Output: 4

Here, the first even number is 4, so it returns 4.


findIndex()

The findIndex() method returns the first index of an element based on a condition.

Example:

const arr = [1, 3, 13, 5, 2, 6];
const evenNumber = arr.findIndex((num) => num % 2 === 0);
console.log(evenNumber); // Output: 4

Here, the first even number is 2, which is at index 4, so findIndex() returns 4.


findLastIndex()

The findLastIndex() method returns the last index of an element based on a condition.

Example:

const arr = [1, 3, 13, 5, 2, 6, 18, 17];
const evenNumber = arr.findLastIndex((num) => num % 2 === 0);
console.log(evenNumber); // Output: 6

Here, the last even number is 18, which is at index 6, so findLastIndex() returns 6.


some()

The some() method checks if at least one element in the array passes a condition (callback function). It returns true if any element passes, otherwise false.

It does not change the array.

Example:

const arr = [1, 2, 3, 4];
const hasEven = arr.some((num) => num % 2 === 0);
 
console.log(hasEven); // Output: true

Here, 2 and 4 are even, so it returns true.


every()

The every() method checks if all elements in the array pass a condition (callback function). It returns true only if every element passes, otherwise false.

It does not change the array.

Example:

const arr = [2, 4, 6];
const allEven = arr.every((num) => num % 2 === 0);
 
console.log(allEven); // Output: true

Here, all elements of the array are even, so it returns true.


at()

The at() method returns the element at the given index. It supports negative indexes, counting from the end of the array.

Example:

const arr = ["a", "b", "c", "d"];
console.log(arr.at(2)); // Output: "c"
console.log(arr.at(-1)); // Output: "d"

forEach()

The forEach() method is useful when you want to call a function once for each element of the array.

Example:

const colors = ["red", "orange", "blue", "green", "white"];
colors.forEach((color) => console.log(color));

Output:

red
orange
blue
green
white

map()

The map() method creates a new array by performing a function on each element of the array.

Syntax:

const newArray = array.map(callback);
  • The callback runs once for each element.
  • It does not modify the original array.
  • The result of each callback becomes an element in the new array.

Example:

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map((num) => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

Here,

  • num => num * num squares each number.
  • map() creates a new array of squared values.

filter()

The filter() method creates a new array by filtering array elements based on a condition.

It does not change the original array. It creates a new one.

Syntax:

const newArray = array.filter(callback);

Here,

  • The filter() method takes a callback function as an argument. This function is executed for each element of the array.
  • If the condition in the callback function returns true, the element is added to the new array. If it returns false, the element is skipped.

Example:

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6]

Here,

  • num % 2 === 0 checks if a number is even.
  • Only even numbers pass the condition and are added to the new array.

If no elements satisfy the condition, filter() returns an empty array.

Example:

const nums = [1, 3, 5];
const greaterThan10 = nums.filter((num) => num > 10);
console.log(greaterThan10); // Output: []

reduce()

The reduce() method can be used to reduce an array to a single value by performing a function on each element of the array.

Syntax:

array.reduce((accumulator, currentValue, currentIndex, array) => {
  // function logic
}, initialValue);
  • accumulator: Holds the result of the previous computation.
  • currentValue: The current element being processed.
  • currentIndex(optional): The index of the current element.
  • array(optional): The array being traversed.
  • initialValue(optional): The starting value for the accumulator.

Example:

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 10

Here,

  • Starts with acc = 0 (initial value).
  • Adds each element to acc:
    • 0 + 1 = 1
    • 1 + 2 = 3
    • 3 + 3 = 6
    • 6 + 4 = 10
  • So the output is 10.

reduceRight()

The reduceRight() method applies a function against an accumulator and each element of the array (from right to left) to reduce it to a single value.

It works like reduce(), but starts from the last element and moves to the first.

Example:

const arr = ["a", "b", "c"];
const result = arr.reduceRight((acc, curr) => acc + curr, "");
 
console.log(result); // Output: "cba"

Here,

  • Starts with acc = "" (empty string as the initial value).
  • Combines elements from right to left:
    • "" + "c" = "c"
    • "c" + "b" = "cb"
    • "cb" + "a" = "cba"
  • So the output is "cba".

flat()

The flat() method creates a new array by flattening nested arrays into a single-level array.

By default, it flattens only one level deep.

Example:

const nested = [1, [2, 3], [4, [5]]];
const flatOne = nested.flat();
 
console.log(flatOne); // Output: [1, 2, 3, 4, [5]]

Here,

  • The original array has nested arrays [1, [2, 3], [4, [5]]].
  • flat() goes one level deep:
    • 1 stays as is
    • [2, 3] becomes 2, 3
    • [4, [5]] becomes 4, [5]
  • So the output is [1, 2, 3, 4, [5]].

You can also pass a number to specify how many levels deep to flatten.

Example:

const nested = [1, [2, 3], [4, [5]]];
const flatAll = nested.flat(2);
console.log(flatAll); // Output: [1, 2, 3, 4, 5]

Here,

  • The original array is [1, [2, 3], [4, [5]]].
  • Using flat(2) means flatten the array 2 levels deep.
  • So [4, [5]] becomes [4, 5] after flattening.
  • So the output is [1, 2, 3, 4, 5].

flatMap()

The flatMap() method first maps each element using a function, then flattens the result by one level.

It's a combination of map() and flat().

Example:

const arr = [1, 2, 3];
const result = arr.flatMap((x) => [x, x * 2]);
 
console.log(result); // Output: [1, 2, 2, 4, 3, 6]

Here,

  • For each element x in arr, the callback returns [x, x * 2].
  • So:
    • 1 becomes [1, 2]
    • 2 becomes [2, 4]
    • 3 becomes [3, 6]
  • flatMap() then flattens these arrays into a single array:
    • [1, 2] becomes 1, 2
    • [2, 4] becomes 2, 4
    • [3, 6] becomes 3, 6
  • So the output is [1, 2, 2, 4, 3, 6].

sort()

The sort() method sorts the array elements alphabetically.

Example:

const arr = ["a", "z", "s"];
arr.sort();
console.log(arr); // Output: ['a', 's', 'z']
 
const colors = ["red", "blue", "white"];
colors.sort();
console.log(colors); // Output: ['blue', 'red', 'white']

When you use the sort() method to sort an array of numbers, JavaScript converts numbers to strings and sorts them alphabetically (lexicographically), which often gives unexpected results.

Example:

const numbers = [10, 2, 5, 1];
numbers.sort();
console.log(numbers); // Output: [1, 10, 2, 5]

Here,

  • It compares numbers as strings, "1", "10", "2", "5"
  • So "10" comes after "1" but before "2", which is why the order looks wrong.

To sort numbers correctly, provide a compare function:

const numbers = [10, 2, 5, 1];
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 2, 5, 10]

Here,

  • (a, b) => a - b sorts numbers in ascending order.
  • If the result is negative, a comes before b.
  • If positive, b comes before a.
  • If zero, their order stays the same.

reverse()

The reverse() method is used to reverse the elements of the array.

Example:

const colors = ["red", "orange", "blue", "green", "white"];
colors.reverse();
console.log(colors); // Output: ['white', 'green', 'blue', 'orange', 'red']

toSorted()

The toSorted() method returns a new sorted array without modifying the original array.

It sorts elements alphabetically by default (like sort()), but it does not change the original array.

You can also pass a compare function to sort numbers or customize sorting.

Example:

const arr = ["a", "z", "s"];
const sortedArr = arr.toSorted();
 
console.log(sortedArr); // Output: ['a', 's', 'z']
console.log(arr); // Original array stays the same: ['a', 'z', 's']

Sorting numbers without a compare function (wrong order):

const numbers = [10, 2, 5, 1];
const sortedNumbers = numbers.toSorted();
console.log(sortedNumbers); // Output: [1, 10, 2, 5]

Sorting numbers with a compare function (correct order):

const numbers = [10, 2, 5, 1];
const sortedNumbers = numbers.toSorted((a, b) => a - b);
console.log(sortedNumbers); // Output: [1, 2, 5, 10]
console.log(numbers); // Output: [10, 2, 5, 1] (Original array is unchanged)

toReversed()

The toReversed() method returns a new array with the elements in reverse order.

It reverses elements like reverse(), but it does not change the original array.

Example:

const arr = [1, 2, 3];
const reversed = arr.toReversed();
 
console.log(reversed); // Output: [3, 2, 1]
console.log(arr); // Output: [1, 2, 3]

slice()

The slice() method extracts a part of an array and returns a new array with the extracted elements.

It does not change the original array.

  • The first argument is the start index (inclusive).
  • The second argument is the end index (exclusive), slicing stops just before this index.

Example: 1

const array1 = [1, 5, 6];
const newArray1 = array1.slice(1); // starts at index 1 and slice upto the end
console.log(newArray1); // Output: [5, 6]

Example: 2

const array2 = [1, 34, 16, 5, 13];
const newArray2 = array2.slice(1, 3); // starts at index 1 and slice upto index (3-1)
console.log(newArray2); // Output: [34, 16]

Example: 3

const array3 = ["red", "orange", "blue", "green", "white"];
const newArray3 = array3.slice(2, 4); // starts at index 2 and slice upto index (4-1)
console.log(newArray3); // Output: ['blue', 'green']

concat()

The concat() method creates a new array by joining two or more given arrays.

Example:

const arr1 = [1, 9, 13, 7];
const arr2 = ["a", "f", "i"];
 
const arr3 = arr1.concat(arr2);
 
console.log(arr3); // Output: [1, 9, 13, 7, 'a', 'f', 'i']

Array.from()

The Array.from() method creates a new array from any array-like or iterable object, such as strings, sets, or objects with a length property.

Example:

Array.from("ABCDE"); // Output: ['A', 'B', 'C', 'D', 'E']

Here, the string "ABCDE" is converted into an array of individual characters.


toString()

The toString() method converts an array into a string of comma-separated values.

Example:

const colors = ["red", "orange", "blue", "green", "white"];
const colorsString = colors.toString();
 
console.log(colorsString); // Output: red,orange,blue,green,white

join()

The join() method joins all the elements of an array using a given separator.

Example:

const numbers = [1, 9, 13, 7];
 
const numbers1 = numbers.join("-");
const numbers2 = numbers.join("!");
 
console.log(numbers1); // Output: 1-9-13-7
console.log(numbers2); // Output: 1!9!13!7

entries()

The entries() method returns a new iterator object that contains [index, value] pairs for each array element.

Example:

const arr = ["a", "b", "c"];
const iterator = arr.entries();
 
for (const [index, value] of iterator) {
  console.log(index, value);
}
 
// Output:
// 0 "a"
// 1 "b"
// 2 "c"

You can use this to loop over both the index and value of an array easily.


keys()

The keys() method returns a new iterator object containing the keys (indexes) for each element in the array.

Example:

const arr = ["a", "b", "c"];
const iterator = arr.keys();
 
for (const key of iterator) {
  console.log(key);
}
 
// Output:
// 0
// 1
// 2

values()

The values() method returns a new iterator object containing the values for each element in the array.

Example:

const arr = ["a", "b", "c"];
const iterator = arr.values();
 
for (const value of iterator) {
  console.log(value);
}
 
// Output:
// "a"
// "b"
// "c"

Support my work!