15+ Must-Know Javascript Array Methods

Posted in

15+ Must-Know Javascript Array Methods
sangeeta.gulia

Sangeeta Gulia
Last updated on December 10, 2024

    An array is a special kind of object in JavaScript that allows us to store multiple values in a single variable. Every value inside the array is stored against a unique key called an index. When we wish to store a list of elements and access them with a single variable, a JavaScript array comes in handy. Unlike other programming languages where an array is simply a reference to multiple variables, in JavaScript , it is a single variable storing multiple elements.

    The array objects are frequently used as built-in global objects of Javascript. It provides a lot of functionality and ease in simplifying complex algorithms. Furthermore, JavaScript provides numerous array methods that assist you in performing operations on JavaScript arrays .

    In this article, we will browse through the different types of array methods and will discuss their functioning. Prior to it, let us first understand how to create arrays in JavaScript.

    So, let us get started!

    Ways to Create Javascript Arrays

    Before forging ahead, as prerequisites, we should know how to create arrays in Javascript.

    Type 1

    Array is initialized while declaring.

    var cars = ["XUV700", "Jeep", "Seltos", "Swift"];

    Type 2

    Use the constructor to create an array, as follows:

    var cars = newArray("XUV700");

    Type 3

    Initially, create an array with the help of a constructor. As soon as you initialize an array of a fixed length, start pushing elements inside it.

    var cars = newArray(2);
    
    cars.push("XUV700");
    cars.push("Jeep");

    Javascript Array Methods

    In JavaScript, array methods are built-in or pre-coded functions that you can use with arrays to perform a change or calculation on arrays. These methods significantly save the time required for writing JS code from scratch. You can simply use the JS method to accomplish a specific task.

    The categorization of JS array methods above is fundamental, considering some of the JS Array methods that are known to me. We will try to cover some of the major methods from the above list in this article.

    An array object in Javascript provides many features through its functions. The user can iterate, sort, and splice the elements in an array with the help of these functions.

    The following is a list of methods currently used in JS for array objects.

    1. concat()

    Javascript concat() method merges two or more arrays or values provided as arguments. The return value of this operation is an array object representing the concatenated values/arrays. It first merges the elements of the calling array and then pushes the elements of the array passed in the argument.

    Syntax

    arr.concat();
    arr.concat(value1, value2, ..., valueN);

    Parameters

    valueN: It can be any value or an array that can concatenate into the calling array. It sends a shallow copy of the calling array if nothing is passed.

    Returns

    A new array instance.

    Example

    Merge the two arrays and some values.

    const evenNumbers = [2,4,6];
    const oddNumbers = [1,3,5];
    
    const result = evenNumbers.concat(oddNumbers, 0, [7,8]);
    console.log(result);

    Output

    Array [2, 4, 6, 1, 3, 5, 0, 7, 8]

    2. every()

    The Javascript every() method checks whether all the elements in an array meets the specified condition. It executes the callback function provided in the argument for each array element until it finds a false value. It doesn’t mutate the array on which it is iterated.

    This method is a Javascript extension to the ECMA-262 standards. Please check its availability before use.

    Syntax

    arr.every(element);
    arr.every(callbackFunction);

    Parameters

    element : items of an array.

    callbackFunction: This function iterates over each element of an array and checks for the falsy value.

    Returns

    This returns true if the callbackFunction returns a truthy value for every array element. Otherwise, false.

    Example

    Example 1: Check if all the elements in an array are even.

    const arr = [10, 348, 31, 21];
    
    //checks if all elements in an array are even
    console.log(arr.every((element) => (element % 2) === 0));

    Output

    false

    Example 2: Check if all the elements in an array are odd.

    let arr = [9, 31, 57, 21];
    
    functionisOdd(element) {
    return (element % 2) !== 0;
    
    }
    
    //checks if all elements in an array are odd
    console.log(arr.every(isOdd));

    Output

    true

    3. filter()

    The Javascript filter() method creates and returns a shallow copy of the elements which pass the specified condition.

    Syntax

    arr.filter(element);
    arr.filter(callbackFunction);

    Parameters

    element: items of an array.

    callbackFunction: This function iterates over each element of an array and checks for the matching value.

    Returns

    An instance of an array.

    Example

    Example 1: Filter out all elements in an array, multiples of 10.

    const arr = [10, 348, 31, 21];
    
    //returns multiple of 10
    console.log(arr.filter((element) => (element % 10) === 0));

    Output

    Array [10]

    Example 2: Filter out all elements of an array which are greater than 100 using function.

    const arr = [900, 31, 57, 21];
    
    functiongetAllElementsLessThan100(element) {
    return element < 100 ;
    
    }
    
    //get all elements less than 100
    console.log(arr.filter(getAllElementsLessThan100));

    Output

    Array [31, 57, 21]

    4. forEach()

    Javascript forEach() method invokes and executes a function for each element of an array. It is not invoked for the values which are deleted or not initialized. You cannot stop or break the forEach loop unless throwing the exception manually.

    Syntax

    arr.forEach(element);
    arr.forEach(callbackFunction);

    Parameters

    element: items of an array.

    callbackFunction: This function iterates over each element of an array.

    Returns

    undefined

    Example

    Iterate over the elements of the array and increase the value by 5.

    const arr = [1, 2, 3];
    //Display all elements of array after increasing them by 5
    arr.forEach(element => console.log(element + 5));

    Output

    6
    7
    8

    5. includes()

    The Javascript includes() method checks whether the array contains the searched element and returns true or false based on that.

    Syntax

    arr.includes(searchedElement)

    Parameter

    searchedElement - element to be checked.

    Returns

    True - if the element is present in the array.

    False - if the element is not present in the array.

    Example

    const array1 = [21, 24, 33];
    
    console.log(array1.includes(2));
    console.log(array1.includes(24));

    Output

    false
    true

    6. indexOf()

    The Javascript indexOf() method returns the first index at which the required element is present in an array. It provides -1 if the necessary element is not present in the array.

    Syntax

    arr.indexOf(searchedElement)
    arr.indexOf(searchedElement, fromIndex)

    Parameters

    searchedElement: It is the element of which we need to find the index.

    fromInde x: This is optional in this method. This is the index from which you want to start the search.

    Returns

    An index if the item is found in the array.

    Returns -1 - If the item is not present in the array.

    Example

    Find the index of all elements in the array.

    const arr = [6, 7, 8];
    console.log(arr.indexOf(6));
    console.log(arr.indexOf(5));

    Output

    0
    -1

    7. join()

    The Javascript join() method concatenates the elements of an array and creates a string separated by a comma or a separator. If the array contains only one element, then only that item will be returned without a separator.

    Syntax

    arr.join(separator)

    Parameter

    Separator: It is the unique character by which you want to join the elements of the array.

    Returns

    String.

    Example

    const arr = ['tech', 'geek', 'buzz'];
    console.log(arr.join());
    console.log(arr.join(""));
    console.log(arr.join("-"));

    Output

    "tech,geek,buzz"
    "techgeekbuzz"
    "tech-geek-buzz"

    8. lastIndexOf()

    The Javascript lastIndexOf() method returns the last index where the required element can be found. It returns -1 if the element is not present.

    Syntax

    arr.lastIndexOf(element)
    arr.lastIndexOf(element, fromIndex)

    Parameter

    Element: It is the element which we need to check inside the array.

    fromIndex: It is the index element from where the search should start.

    Returns

    The last index of the searched element.

    -1 if the element is not present.

    Example

    const figherJets = ['F16', 'Jaguar', 'SU30', 'Jaguar'];
    console.log(figherJets.lastIndexOf('Jaguar'));
    console.log(figherJets.lastIndexOf('SU30'));

    Output

    3
    2

    9. map()

    The Javascript map() method creates a new array containing the results of executing a function on each element on the array. If you are not expecting an array in return for this operation, you should not use map(). Use forEach, instead.

    Syntax

    arr.map(element);
    arr.map(callbackFunction);

    Parameters

    element: the element on which map to be performed.

    callbackFunction: function to iterate through each element.

    Returns

    A new array with each element being the result of the callback function.

    Example

    Finding the cube of each element in the array.

    const arr = [1, 4, 9, 16];
    
    // pass a function to map
    console.log(arr.map(x => x * x * x));

    Output

    Array [1, 64, 729, 4096]

    10. pop()

    The Javascript pop() method removes the last element from the array and returns that element. This method manipulates the array and changes the length of the array.

    Syntax

    arr.pop()

    Parameters

    No Parameter

    Returns

    The removed element from the array.

    undefined if the array is empty.

    Example

    const arr = [1, 4, 9, 16];
    console.log(arr.pop());

    Output

    16

    11. push()

    The Javascript push() method inserts a single or more than one element into the array. The insertion is always done at the end. It increases the length of the array.

    Syntax

    arr.push();

    Parameters

    No Parameters

    Returns

    It returns the length of the new array after the pushing is performed.

    Example

    const arr = [1, 4, 9, 16];
    console.log(arr.push());

    Output

    5

    12. reverse()

    The Javascript reverse() method reverses the elements in an array and returns the references of this array. After performing this operation on an array, the first element becomes the last, and the last becomes the first element in the array.

    Syntax

    arr.reverse();

    Parameters

    No Parameters.

    Returns

    The reference of the new array.

    Example

    const arr = [18, 24, 69, 16];
    console.log(arr.reverse());

    Output

    Array [16, 69, 24, 18]

    13. shift()

    The Javascript shift() method removes the first element of the array and returns that element. It changes the length of the array.

    Syntax

    arr.shift()

    Parameters

    No Parameters

    Returns

    The element that has have been removed from the array.

    Example

    const arr = [18, 24, 69, 16];
    console.log(arr.shift());

    Output

    18

    14. slice()

    The Javascript slice() method creates and returns a shallow copy from the original array. The original array is not modified here.

    Syntax

    arr.slice()
    arr.slice(start)
    arr.slice(start, end)

    Parameters

    start: zero-based index at which extraction of new array will start.

    end: zero-based index at which extraction of new array will end.

    Returns

    A new array containing the extracted elements.

    Example

    const states = ['DL', 'JK', 'UK', 'HP', 'UP', 'GA'];
    
    console.log(states.slice(3));
    
    console.log(states.slice(2, 5));
    
    console.log(states.slice(3, 5));
    
    console.log(states.slice(-2));
    
    console.log(states.slice(3, -1));
    
    console.log(states.slice());

    Output

    Array ["HP", "UP", "GA"]
    Array ["UK", "HP", "UP"]
    Array ["HP", "UP"]
    Array ["UP", "GA"]
    Array ["HP", "UP"]
    Array ["DL", "JK", "UK", "HP", "UP", "GA"]

    15. some()

    The Javascript some() method tests if any element in the array passes the test the function provides. It returns true if at least one of the elements passes the test.

    Syntax

    arr.some(element);
    arr.some(element, index);
    arr.some(callbackFunction)

    Parameters

    element: the current element being processed.

    index: the index of the current element.

    callbackFunction: the test function.

    Returns

    It returns true if at least one of the elements passes the test.

    It returns false if no element passes the test.

    Example

    Example 1 - Check if all elements are multiple of 100

    const arr = [100, 200, 300, 400];
    const multipleOfHundred = (element) => element % 100 === 0;
    console.log(arr.some(multipleOfHundred));

    Output

    true

    Example 2 - Check if all elements are multiple of 5

    const arr = [1, 2, 3, 4];
    const multipleOfFive = (element) => element % 5 === 0;
    console.log(arr.some(multipleOfFive));

    Output

    false

    16. sort()

    The Javascript sort() method sorts the elements of the array. It doesn’t change the length of the array. It takes a callback function as an argument. If no function is provided, it sorts lexicographically.

    Syntax

    arr.sort();
    arr.sort(compareFunction);

    Parameters

    compareFunction: This function contains the order of sorting.

    Returns

    The reference of the sorted array. This is not a new array but the original one, sorted.

    Example

    const months = ['X', 'C', 'Z', 'F', 'A'];
    console.log(months.sort());

    Output

    Array ["A", "C", "F", "X", "Z"]

    17. toString()

    The Javascript toString() method returns a string after converting all the elements of an array into a string.

    Syntax

    arr.toString()

    Parameters

    No Parameter

    Returns

    String

    Example

    const months = ['T', 'G', 'B'];
    console.log(months.toString());

    Output

    "T,G,B"

    Conclusion

    In this article, we have gone through almost 17 Javascript Array methods. There is a long list of JS methods available. You can start doing hands-on on all the available methods. Also, it will help if you start solving FAQs or interview questions. When you start solving interview questions, you will learn more enriching features of array methods. The more you make your hands dirty in this, the easier it will be for you to grasp.

    Please contact us through email if you find any section in this article confusing or complex. We will be more than happy to assist you. Otherwise, if you have any doubts, please feel free to put up a comment. We will reply as soon as possible.

    Thank you for your time.

    People are also reading:

    FAQs


    Array methods in JS are built-in functions that you can apply on arrays directly to perform calculations or changes in arrays.

    All the array methods available in JavaScript are categorized into seven groups: Add/Remove, Flattening, Search, High Order, Manipulation, Array to String, and Creation.

    The high order JS array methods include map(), filter(), reduce(), sort(), every(), some()< and forEach().

    The pop() array method removes the last element from an array, which manipulates the length of the array, and returns the popped element as output.

    The JavaScript forEach method calls the specified function for every element in an array. It is not used with empty arrays.

    Leave a Comment on this Post

    0 Comments