JavaScript Array map() Method

 .map() returns a new array of elements where you have applied some function on the element so that it changes the original element.

Explanation:

You already have an array with values.

let details = [
  {id: "1", lastName: "Node js"},
  {id: "2", lastName: "Angular js"},
  {id: "3", lastName: "React js"}
];

And you want only name from the array:
[Node js, Angular js, React js]

So, here we use the map() function of JavaScript: The  Array.map() method allows you to iterate over an array and modify its elements using a callback function. 


How to use map()

var newArray = details.map(function (data) {

  return data.name

});

Here, newArray is a new Array that stores the value which has been map. Here data(Can name as per you want) variable is used to store all details array values. Then, data.name will return all the values having the name in the data(details) array.

Can also use ES6 arrow function:

var newArray= details.map(data => {

return data.name

});


OUTPUT: 
[Node js , Angular js, React js]




    NOTE: 

  • map() form a new Array, it does not affect the original Array. To modify the Original array, map() can't be used. 
  • map() does not execute the function for array elements without values.


    Using map():

    1) Multiplying array with a specific number

    let array = [1, 2, 3, 4];

    let newArray= array.map(function(element){
        return element *3;
    });
Output: [1, 4, 9, 16]

  2) To join the values
let users = [
  {firstName : "Software", lastName: "Developer"},
  {firstName : "Web", lastName: "Technology"}
 ]

let userFullnames = users.map(function(element){
    return `${element.firstName} ${element.lastName}`;
})

OUTPUT:
["Software Developer", "Web Technology"]

Comments

Popular posts from this blog

Entrepreneur

Slumdog Millionaire - Kalpana Saroj

Mental health - Depression