JavaScript map function | map array of objects with example

Created At: 2021-03-24 04:25:14 Updated At: 2021-03-25 16:37:44

You will learn about JavaScript map() function.

This function is useful when you want to loop through an array and find the current value for the indexes in the array. Remember not finding the indexes, rather we find the index value.

It takes two parameters

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

1. First one is a function that takes three params. Like function(currentValue, index, arrHold)

2. Second one is thisValue. This is optional

See an example how to use map() method to find or retrieve the current value for the indexes.

<!DOCTYPE html>
<html>
<head>
    <title>
        JavaScript splice() Method remove item
    </title>
</head>
  
<body>  
    <script>
        let arr=["45", "47", "50"];
        arr.map(function(currentValue, index, arrHold){
              console.log(currentValue);
        })
    </script>
</body>
  
</html>

The above map method loops through the array three times and calls the inside function and output is

45, 47, 50

map() method is run for every element in the arr and calls the anonymous function for each element. The first parameter currentValue inside the function is the current value for the object. In our example currentValue should be 45 and index would be 0. Second time map() method calls the function for the second object. For the second object, the currentValue would be 47 and index would be 1

<!DOCTYPE html>
<html>
<head>
    <title>
        JavaScript Array map() Method example
    </title>
</head>
  
<body>
    <script>
          var arr=[4, 5, 6, 7];
          arr.map(function(item, index){
                 console.log(item*item);
          });
    </script>
</body>
  
</html>

The output of the below function is

16, 25, 36, 49

 

Comment

Add Reviews