JavaScript - map() method

Revision:


Category : array

The map() method creates a new array with the results of calling a function for every array element. The map() method calls the provided function once for each element in an array, in order. The method does not execute the function for empty elements and does not change the original array.

The "Array.map() method" allows you to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each of the array's elements.

Syntax :

        array.map(function(currentValue, index, arr), thisValue)
    

Parameter values:

function(currentValue, index, arr): required; a function to be run for each element in the array. Function arguments:

- currentValue: required ; the value of the current element.
- index : optional; the array index of the current element.
- arr : optional; the array object the current element belongs to.

thisValue : optional; a value to be passed to the function to be used as its "this" value; if this parameter is empty, the value "undefined" will be passed as its "this" value.

Examples:

        const array1 = [1, 4, 9, 16];
        // Pass a function to map
        const map1 = array1.map(x => x * 2);
        console.log(map1);
       // Expected output: Array [2, 8, 18, 32]
    

Practical examples

example: create a new array.

code:

                    <script>
                        const numbers_B = [4, 9, 16, 25];
                        document.getElementById("map-01").innerHTML = "numbers: " + numbers_B;
                        document.getElementById("map-02").innerHTML = "square root: " + numbers_B.map(Math.sqrt);
                    </script>
                

example: multiply every element in the array.

code:

                    <script>
                        const numbers_a = [65, 44, 12, 4];
                        document.getElementById("map-03").innerHTML = "numbers: " + numbers_a;
                        const newArr = numbers_a.map(myFunction);
                        document.getElementById("map-04").innerHTML = "function: *10: " + newArr;              
                        function myFunction(num) {
                            return num * 10;
                        }
                    </script>
                

example: compute a new array

code:

                    <script>
                        const persons = [
                            {firstname : "Willem", lastname: "Verbiest"},
                            {firstname : "Karel", lastname: "Vansteen"},
                            {firstname : "Elodie", lastname: "Wouters"}
                        ];
                        document.getElementById("map-05").innerHTML = persons.map(getFullName);
                        function getFullName(item) {
                            return [item.firstname,item.lastname].join(" ");
                        }
                </script>
                

example: compute a new array

code:

                    <script>
                        let users = [
                            {firstName : "Susan", lastName: "Wellens"},
                            {firstName : "Daniel", lastName: "Verelst"},
                            {firstName : "Jos", lastName: "Verstappen"}
                        ];
                        let userFullnames = users.map(function(element){
                            return `${element.firstName} ${element.lastName}`;
                        })
                        document.getElementById("map-06").innerHTML = userFullnames;
                    </script>
                

example: compute a new array

code:

                    <script>
                        const users_a = [
                            {name: 'Theo Waelbers', age: 35},
                            {name: 'Lea Wellens', age: 24},
                            {name: 'Alex Brouns', age: 42}
                        ];
                        const ages = users_a.map(user => user.age);
                        console.log(ages);
                        document.getElementById("map-07").innerHTML = ages;
        
                        let modifiedUsers = users_a.map(user => {
                        // assign a random color to each user
                        user.color = '#' + (Math.random() * 0xFFFFFF << 0).toString(16) +"< br>";
                        // return modified user
                        return user;
                        });
                        
                        console.log(modifiedUsers);
                        document.getElementById("map-08").innerHTML = JSON.stringify(modifiedUsers);
                    </script>