JavaScript Array Methods

JavaScript Array Methods

An array is a special variable, which can hold more than one value. JavaScript provides a variety of methods for manipulating arrays. Working with arrays could be difficult sometimes if you don't know the right methods to use, when to use them and how to use them. Knowing these help to sort of simplify

While reading about these methods, keep in mind that some of them modify the array they are called on and some of them leave the array unchanged. A number of the methods return an array: sometimes, this is a new array, and the original is unchanged. Other times, a method will modify the array in place and will also return a reference to the modified array.

Here's a comprehensive list of commonly used array methods in JavaScript:

  1. Adding/Removing Elements:

    • push(element1, ..., elementN): Adds one or more elements to the end of an array and returns the new length of the array.

        let fruits = ['apple', 'orange'];
        fruits.push('banana', 'grape');
        // fruits is now ['apple', 'orange', 'banana', 'grape']
      
    • pop(): Removes the last element from an array and returns that element.

        let fruits = ['apple', 'orange', 'banana'];
        let removedFruit = fruits.pop();
        // fruits is now ['apple', 'orange'], removedFruit is 'banana'
      
    • shift(): Removes the first element from an array and returns that element.

        let fruits = ['apple', 'orange', 'banana'];
        let removedFruit = fruits.shift();
        // fruits is now ['orange', 'banana'], removedFruit is 'apple'
      
    • unshift(element1, ..., elementN): Adds one or more elements to the beginning of an array.

        let fruits = ['orange', 'banana'];
        fruits.unshift('apple', 'grape');
        // fruits is now ['apple', 'grape', 'orange', 'banana']
      
    • splice(start, deleteCount, item1, ..., itemN): Changes the contents of an array by removing or replacing existing elements and/or adding new elements.

        let fruits = ['apple', 'orange', 'banana', 'grape'];
        fruits.splice(1, 2, 'pear', 'kiwi');
        // fruits is now ['apple', 'pear', 'kiwi', 'grape']
      
  2. Combining/Slicing Arrays:

    • concat(array2, ..., arrayN): Combines two or more arrays and returns a new array.

        let fruits = ['apple', 'banana'];
        let vegetables = ['carrot', 'broccoli'];
        let combined = fruits.concat(vegetables);
        // combined is ['apple', 'banana', 'carrot', 'broccoli']
      
    • slice(start, end): Returns a shallow copy of a portion of an array.

        let fruits = ['apple', 'orange', 'banana', 'grape'];
        let slicedFruits = fruits.slice(1, 3);
        // slicedFruits is ['orange', 'banana'], fruits is unchanged
      
  3. Searching/Filtering Elements:

    Searching and sorting methods are for locating elements within an array and for sorting the elements of an array

    • indexOf(element, fromIndex): Returns the first index at which a given element is found in the array, or -1 if not present.

        let fruits = ['apple', 'orange', 'banana', 'grape'];
        let bananaIndex = fruits.indexOf('banana');
        // bananaIndex is 2
      
    • lastIndexOf(element, fromIndex): Returns the last index at which a given element is found in the array, or -1 if not present.

        let fruits = ['apple', 'orange', 'banana', 'grape', 'banana'];
        let lastBananaIndex = fruits.lastIndexOf('banana');
        console.log(lastBananaIndex); // Output: 4
      
    • includes(element, fromIndex): Determines whether an array includes a certain element.

        let fruits = ['apple', 'orange', 'banana', 'grape'];
        let hasBanana = fruits.includes('banana');
        console.log(hasBanana); // Output: true
      
    • filter(callback(element, index, array), thisArg): Creates a new array with all elements that pass the test implemented by the provided function.

        let numbers = [1, 2, 3, 4, 5, 6];
        let evenNumbers = numbers.filter(function (num) {
          return num % 2 === 0;
        });
        console.log(evenNumbers); // Output: [2, 4, 6]
      
  4. Iterating Over Elements:

    Iterator methods loop over the elements of an array, typically invoking a function that you specify on each of those elements. All of these methods accept a function as their first argument and invoke that function once for each element (or some elements) of the array

    • forEach(callback(currentValue, index, array), thisArg): Executes a provided function once for each array element.

        let fruits = ['apple', 'orange', 'banana'];
        fruits.forEach(function (fruit, index) {
          console.log(index, fruit);
        });
        // Output: 0 apple, 1 orange, 2 banana
      
    • map(callback(currentValue, index, array), thisArg): Creates a new array with the results of calling a provided function on every element.

        let numbers = [1, 2, 3, 4, 5];
        let squaredNumbers = numbers.map(function (num) {
          return num * num;
        });
        console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
      
    • every(callback(currentValue, index, array), thisArg): Tests whether all elements in the array pass the provided function.

        let numbers = [2, 4, 6, 8, 10];
        let allEven = numbers.every(function (num) {
          return num % 2 === 0;
        });
        console.log(allEven); // Output: true
      
    • some(callback(currentValue, index, array), thisArg): Tests whether at least one element in the array passes the provided function.

        let numbers = [1, 3, 5, 7, 8];
        let hasEven = numbers.some(function (num) {
          return num % 2 === 0;
        });
        console.log(hasEven); // Output: true
      
  5. Reducing/Aggregating Elements:

    • reduce(callback(accumulator, currentValue, index, array), initialValue): Applies a function against an accumulator and each element in the array to reduce it to a single value.

        let numbers = [1, 2, 3, 4, 5];
        let sum = numbers.reduce(function (accumulator, currentValue) {
          return accumulator + currentValue;
        }, 0);
        console.log(sum); // Output: 15
      
    • reduceRight(callback(accumulator, currentValue, index, array), initialValue): Applies a function against an accumulator and each element in the array (from right to left) to reduce it to a single value.

        let numbers = [1, 2, 3, 4, 5];
        let subtractRight = numbers.reduceRight(function (accumulator, currentValue) {
          return accumulator - currentValue;
        }, 0);
        console.log(subtractRight); // Output: -5 (5 - (4 - (3 - (2 - 1))))
      
  6. Sorting Elements:

    • sort(compareFunction): Sorts the elements of an array in place.

        let fruits = ['banana', 'apple', 'orange', 'grape'];
        fruits.sort();
        console.log(fruits); // Output: ['apple', 'banana', 'grape', 'orange']
      
    • reverse(): Reverses the elements of an array in place.

        let numbers = [1, 2, 3, 4, 5];
        numbers.reverse();
        console.log(numbers); // Output: [5, 4, 3, 2, 1]
      

These methods provide powerful tools for working with arrays in JavaScript, allowing you to manipulate, search, iterate, and aggregate array elements efficiently.