How to Use Javascript map() Array?

Posted in

How to Use Javascript map() Array?

Paritosh Louhan
Last updated on November 30, 2022

    JavaScript provides various methods to iterate over the elements of an array, from ‘ for loop ’ to ‘foreach()’ method. Among all, map() is the most popular one. The map() method returns a new array, with each element being the result of the callback function. It iterates over each element and prints the manipulated result.

    Rather than using a loop to iterate over an array manually, we can use the built-in JavaScript .map() function.

    This article will help you understand everything about the JavaScript map() method. But prior to it, let us understand with an example how you need to iterate an array without using the map() method.

    Iterating Array Elements Without JavaScript map()

    Consider an example when the user wants to print the cube of each element of the array. Without the map method, we might use a for loop to print the result.

    let arr = [1,3,5,7];
    for(let i=0; i<arr.length; i++) {
    console.log(arr[i]*arr[i]*arr[i]);
    }

    Output

    1
    27
    125
    343

    This is the traditional way of printing the required array output. It was widely accepted in previous times until the map method came to the rescue. We can print the same output with fewer lines of code using the map method.

    What is the JavaScriptmap() Method?

    The map() method returns a new array populated with the results of calling a callback function on each element of the array. It makes the code reading very easy and helps the developer to understand quickly.

    The following are the basic characteristics of the map():

    • Doesn’t change the array it is called upon.
    • Does not execute a callback for array elements that are undefined.
    • Executes callback of each element of the array in order.
    • The elements of the returned array are the result of the callback function.

    We have tried to implement the example covered in the Introduction section by using the map() method. And guess what? It is completed in just one line.

    Here is the code snippet.

    arr.map((x) => x*x*x);

    Output

    [1, 27, 125, 343]

    That’s it! It is exponentially simple to write and understand. Isn’t it? Note that, in the for loop, there were four different elements in the output, but in the map method, there is an array of 4 elements.

    Let's further understand the parameters of the map method.

    Syntax

    The following are the types of supported syntaxes for using map methods.

    Syntax 1

    map((item, index, arr) => { /* .code.. */ })

    Syntax 2

    map(callbackFunction, this)

    Syntax 3

    map(function (item, index, arr) { /* .code.. */ }, this)

    Parameters in the JavaScript map() Method

    As seen in the syntax above, the map function takes some parameters. A detailed description with examples is also provided below.

    • item

    An item is a current element that is being processed in the iteration. It is the part of the calling array and gets manipulated during the execution. In the example above, to find the cube of each element of the array, ‘x’ is the item.

    • index

    It is the index of the current element being processed. An example to understand this is provided below.

    arr.map((x, i) => {console.log(i)});

    Output

    0
    1
    • array

    It is the array on which the map function is called upon. Like in all the examples above, ‘arr’ is the array that was being processed.

    • callbackFunction

    This function is used in the execution of each element in the array.

    • this

    This parameter is used as a context variable while using the callback function.

    Usage

    Let us now understand the different use cases of the map() method.

    • Using map() to iterate over the objects in the array

    Here, we will use the map() function to iterate through the array of JS objects . We can do any manipulation based on any property of the object.

    A basic example of this is shown below.

    const arr = [
    { num1: 1, num2: 40 },
    { num1: 2, num2: 50 },
    { num1: 3, num2: 60 },
    ];
    
    arr.map(({ num1, num2 }) => ({ multiplication: num1 * num2 }));

    Output

    0: {multiplication: 40}
    1: {multiplication: 100}
    2: {multiplication: 180}
    • Using map() on a JS object

    One of the uses of map() is to use it over the properties of a JS object. If there is a length property available in the JS object, it will read that and then iterate through the integer indices.

    A basic example of this is shown below.

    const studentsRoll = {
    length: 4,
    0: 242,
    1: 244,
    2: 245,
    3: 246,
    };
    console.log(Array.prototype.map.call(studentsRoll, (x) => x));

    Output

    (4) [242, 244, 245, 246]
    • Using map() on DOM elements

    You can fetch the DOM elements with a JS query and iterate over them using map().

    A basic example of this is shown below.

    const items = document.querySelectorAll("div");
    const elements = Array.prototype.map.call(items, ({ value }) => value);
    • Using map() on sparse arrays

    A sparse array is an array where most of the elements are zero or the same. You can use the map method on the sparse array and it will give desired results.

    A basic example of this is shown below.

    let arr = [1,3,5, 0, undefined, 7];
    arr.map((x, index) => {
    console.log(`We are at ${index} and the value is ${x}`);
    });

    Output

    We are at 0 and the value is 1
    We are at 1 and the value is 3
    We are at 2 and the value is 5
    We are at 3 and the value is 0
    We are at 4 and the value is undefined
    We are at 5 and the value is 7
    • Using conditions inside the JS map() function

    You can use any condition during the map function’s iteration. A conditional statement can be used inside the callback function in order to return the modified value.

    Let’s take a look at the example where we need to fetch all elements smaller than 50. Let’s put conditions during the map function’s iteration.

    const arr = [0, 5, 50, 75, 100];
    
    console.log(arr.map(number => {
    if (number <= 50) {
    return number;
    }
    }));

    Output

    0, 5, 50
    • Using map() with a callback function with all parameters

    This is the most used example of the map. It contains a callback function and all the parameters that it can receive.

    A basic example of the same is provided below.

    let arr = [12, 30, 55, 777, 8]
    
    arr.map(function(element, index, array){
    console.log(element, index, array);
    return element;
    });

    Output

    12 0 (5) [12, 30, 55, 777, 8]
    
    30 1 (5) [12, 30, 55, 777, 8]
    
    55 2 (5) [12, 30, 55, 777, 8]
    
    777 3 (5) [12, 30, 55, 777, 8]
    
    8 4 (5) [12, 30, 55, 777, 8]

    Compatibility

    The browser compatibility of the map() function is displayed below.

    Browser Compatibility of JS map Source

    Conclusion

    This is a complete guide for the JS map() function. We have tried to cover almost all the use cases required to understand the operation of the map() function.

    If you find it useful, then please leave us a comment in the comments section below. If you come across any other useful use case for the map() function, please do let us know via comments.

    Thanks for reading.

    People are also reading:

    Leave a Comment on this Post

    0 Comments