Array methods in JavaScript


Arrays are a fundamental data structure in JavaScript, allowing developers to store and manipulate collections of elements. JavaScript provides a variety of built-in array methods that make it easy to work with arrays efficiently. These methods simplify tasks like adding, removing, sorting, filtering, and transforming array elements.

Array methods in JavaScript

Here's a categorization of JavaScript array methods based on their purpose or the type of operations they perform:

1. Adding and Removing Elements

These methods modify the array by adding or removing elements.

  • push(): Adds elements to the end of the array.
  • pop(): Removes the last element from the array.
  • unshift(): Adds elements to the beginning of the array.
  • shift(): Removes the first element from the array.
  • splice(): Adds/removes/replaces elements at a specific index.

push() and pop()

  • push(): Adds one or more elements to the end of an array and returns the new length of the array.
  • pop(): Removes the last element from an array and returns that element.

Example:

let fruits = ['apple', 'banana'];
fruits.push('orange'); // ['apple', 'banana', 'orange']
fruits.pop(); // ['apple', 'banana']

shift() and unshift()

  • shift(): Removes the first element from an array and returns it. This method changes the length of the array.
  • unshift(): Adds one or more elements to the beginning of the array and returns the new length.

Example:

let fruits = ['apple', 'banana'];
fruits.shift(); // 'apple', ['banana']
fruits.unshift('mango'); // ['mango', 'banana']

splice()

  • Adds, removes, or replaces elements in an array. Unlike slice(), splice() modifies the original array.

Example:

let fruits = ['apple', 'banana', 'orange'];
fruits.splice(1, 1, 'grape'); // ['apple', 'grape', 'orange']

In this example, the method removes 1 element at index 1 ('banana') and replaces it with 'grape'.

2. Accessing, Extracting and Searching Elements

These methods are used to retrieve or extract elements from an array without modifying the original array.

  • slice(): Extracts a portion of the array.
  • find(): Finds the first element that satisfies a condition.
  • findIndex(): Finds the index of the first element that satisfies a condition.
  • includes(): Checks if an element exists in the array.
  • indexOf(): Finds the index of a specific element.
  • lastIndexOf(): Finds the last occurrence of an element.
  • some(): Checks if at least one element passes the condition.
  • every(): Checks if all elements pass the condition.

slice()

  • Extracts a section of the array and returns a new array. It does not modify the original array. The method takes two parameters: the start index (inclusive) and the end index (exclusive).

Example:

let numbers = [1, 2, 3, 4, 5];
let sliced = numbers.slice(1, 4); // [2, 3, 4]

find()

  • Returns the first element in the array that satisfies a given condition. If no such element is found, it returns undefined.

Example:

let numbers = [1, 2, 3, 4];
let firstEven = numbers.find(num => num % 2 === 0); // 2

findIndex()

  • Similar to find(), but instead of returning the element, it returns the index of the first element that satisfies the condition. If no such element exists, it returns 1.

Example:

let numbers = [1, 2, 3, 4];
let index = numbers.findIndex(num => num > 2); // 2

includes()

  • Determines whether an array contains a specific element. It returns true or false.

Example:

let fruits = ['apple', 'banana', 'orange'];
let hasApple = fruits.includes('apple'); // true

indexOf()

The indexOf() method returns the first index at which a specified element is found in an array. If the element is not found, it returns -1.

Example:

let fruits = ['apple', 'banana', 'orange', 'banana'];

// Find the index of 'banana'
let firstBananaIndex = fruits.indexOf('banana'); // 1

// Find the index of 'orange'
let orangeIndex = fruits.indexOf('orange'); // 2

// Search for an element that does not exist
let grapeIndex = fruits.indexOf('grape'); // -1

// Start search from index 2
let bananaAfterIndex2 = fruits.indexOf('banana', 2); // 3

console.log(firstBananaIndex);  // Output: 1
console.log(orangeIndex);       // Output: 2
console.log(grapeIndex);        // Output: -1
console.log(bananaAfterIndex2); // Output: 3

lastIndexOf()

The lastIndexOf() method returns the last index at which a given element is found in the array, searching backward. If the element is not found, it returns -1.

  • searchElement: The element to locate in the array.
  • fromIndex (optional): The index at which to start searching backward. Defaults to the array's last index.

Example:

let fruits = ['apple', 'banana', 'orange', 'banana', 'apple'];

// Find the last occurrence of 'banana'
let lastBananaIndex = fruits.lastIndexOf('banana'); // 3

// Find the last occurrence of 'apple'
let lastAppleIndex = fruits.lastIndexOf('apple'); // 4

// Search for an element that does not exist
let grapeIndex = fruits.lastIndexOf('grape'); // -1

// Start search backward from index 2 (searching from 'orange' to the left)
let bananaBeforeIndex2 = fruits.lastIndexOf('banana', 2); // 1

console.log(lastBananaIndex);   // Output: 3
console.log(lastAppleIndex);    // Output: 4
console.log(grapeIndex);        // Output: -1
console.log(bananaBeforeIndex2); // Output: 1

every() and some()

  • every(): Tests whether all elements in the array pass the condition implemented by a function. Returns true if all elements pass, otherwise false.
  • some(): Tests whether at least one element in the array passes the condition. Returns true if at least one element satisfies the condition, otherwise false.

Example:

let numbers = [1, 2, 3, 4];
let allEven = numbers.every(num => num % 2 === 0); // false
let someEven = numbers.some(num => num % 2 === 0); // true

3. Iterating Over Arrays

These methods are used to iterate over the array, usually for side effects like logging, performing computations, etc.

  • forEach(): Executes a function for each element in the array.

forEach()

  • Executes a function for each element in an array. It doesn't return a new array but is useful for iterating over elements.

Example:

let numbers = [1, 2, 3];
numbers.forEach((num) => console.log(num));
// Output: 1, 2, 3

4. Transforming Arrays

These methods return a new array that is a transformation of the original array.

  • map(): Transforms each element in the array and returns a new array.
  • filter(): Returns a new array containing elements that satisfy a condition.
  • reduce(): Reduces the array to a single value by accumulating values.
  • reduceRight(): Similar to reduce(), but starts from the last element.

map()

  • Creates a new array by applying a function to every element of the original array without modifying it.

Example:

let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2); // [2, 4, 6]

filter()

  • Returns a new array with all elements that pass a condition specified in a callback function.

Example:

let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0); // [2, 4]

reduce()

  • Reduces an array to a single value by applying a function that accumulates values.

Example:

let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // 10

Here, reduce() sums all the elements of the array.

reduceRight()

The reduceRight() method works similarly to reduce(), but it processes the array from right to left. It applies a function against an accumulator and each value of the array (from right to left) to reduce it to a single value.

Example:

let numbers = [1, 2, 3, 4];

// Using reduceRight to sum the array elements from right to left
let sum = numbers.reduceRight((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum);  // Output: 10

More Complex Example with reduceRight():

let words = ['World', ' ', 'Hello'];

// Using reduceRight to reverse and concatenate the array of strings
let sentence = words.reduceRight((accumulator, currentValue) => {
  return accumulator + currentValue;
}, '');

console.log(sentence);  // Output: "Hello World"

5. Sorting and Reversing

These methods modify the array by sorting or reversing the order of elements.

  • sort(): Sorts the elements of the array.
  • reverse(): Reverses the order of elements.

sort()

  • Sorts the elements of an array in place. By default, it sorts elements as strings, but a custom compare function can be passed for more complex sorting.

Example:

let fruits = ['banana', 'apple', 'orange'];
fruits.sort(); // ['apple', 'banana', 'orange']

let numbers = [10, 5, 20, 15];
numbers.sort((a, b) => a - b); // [5, 10, 15, 20]

reverse()

  • Reverses the elements of an array in place.

Example:

let numbers = [1, 2, 3];
numbers.reverse(); // [3, 2, 1]

6. Combining and Joining Arrays

These methods are used to combine or join arrays or their elements.

  • concat(): Combines two or more arrays into a new array.
  • join(): Joins all elements of the array into a string.

concat()

  • Combines two or more arrays without modifying the original arrays, returning a new array.

Example:

let arr1 = [1, 2];
let arr2 = [3, 4];
let combined = arr1.concat(arr2); // [1, 2, 3, 4]

join()

  • Joins all elements of an array into a string, separated by a specified separator (default is a comma).

Example:

let words = ['Hello', 'World'];
let sentence = words.join(' '); // 'Hello World'

7. Flattening Arrays

These methods deal with arrays that contain nested arrays.

  • flat(): Flattens nested arrays into a single array.
  • flatMap(): Maps each element and then flattens the result.

flat()

  • Flattens nested arrays into a single array to a specified depth. If no depth is provided, it defaults to flattening one level.

Example:

let nestedArray = [1, [2, 3], [4, [5, 6]]];
let flatArray = nestedArray.flat(2); // [1, 2, 3, 4, 5, 6]

flatMap()

  • Maps each element using a function, then flattens the result into a new array. It combines map() and flat() in one method.

Example:

let numbers = [1, 2, 3];
let doubledFlat = numbers.flatMap(num => [num * 2]); // [2, 4, 6]

9. Utility Methods

These are more utility-based methods that don't necessarily change or create arrays but provide useful functionality.

  • length: Property that holds the number of elements in the array.
  • toString(): Converts the array into a string (comma-separated).
  • fill(): Fills the array with a static value from a start to end index.
  • copyWithin(): Copies a section of the array to another location in the array.

Summary Table

CategoryMethods
Adding/Removingpush(), pop(), unshift(), shift(), splice()
Accessing/Extracting/Searchingslice(), find(), findIndex(), includes(), indexOf(), lastIndexOf() ,some(), every()
IteratingforEach()
Transformingmap(), flatMap(), filter(), reduce(), reduceRight()
Sorting/Reversingsort(), reverse()
Combining/Joiningconcat(), join()
Flatteningflat(), flatMap()
Utilitylength, toString(), fill(), copyWithin()

Recommended Posts