Array manipulation using JavaScript Array.map
Method.
Other tutorials in JavaScript Array series.
- Array Manipulation Using JavaScript Filter Method
- Array Manipulation Using JavaScript Map Method
- How to Remove Duplicates from JavaScript Array
- How To Loop Through An Array In JavaScript
Let’s have a look at the following JavaScript code:
let employees = [
{
"first_name": "Hari",
"last_name": "Krishnan"
},
{
"first_name": "Samuel",
"last_name": "Jackson"
},
{
"first_name": "Suriel",
"last_name": "Johnson"
},
{
"first_name": "Roy",
"last_name": "Agasthyan"
}
];
let full_names = []
let name;
for (let i = 0; i < employees.length; i++) {
name = employees[i]["first_name"] + ' ' + employees[i]["last_name"] full_names.push(name)
}
console.log(full_names)
// [ 'Hari Krishnan' ,
// 'Samuel Jackson' ,
// 'Suriel Johnson' ,
// 'Roy Agasthyan' ]
As seen in the above code, you have a list of employees in the employees variable. The purpose of the above code is to iterate through the list of employees and concatenate the first name and second name and create another list with the full name of the employees.
Now let’s see how to accomplish the above task using the JavaScript Map method.
Understanding JavaScript Map Method
From the MDN web docs,
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
The Map method when applied to an array, applies the provided function to each element of the array and returns a new array.
Now let’s see how you can rewrite the above code using the JavaScript Map method and how it reduces the code and improves readability.
Here is how the JavaScript Array can be manipulated to return a new array with the full name of the employees using Map
method:
let full = employees.map(function(emp) {
return emp["first_name"] + ' ' + emp["last_name"]
});
console.log(full)
// [ 'Hari Krishnan',
// 'Samuel Jackson',
// 'Suriel Johnson',
// 'Roy Agasthyan' ]
As seen in the above code, you have applied the JavaScript map method to the employees array.
Each item inside the array is being applied the the callback function where the employee first name and last name are being concatenated to return the full name.
The map method returns a new array with the full name of the employees. Now if you compare the above two set of codes, you can see the following plus points:
- You can get rid of the for loop
- You don’t need the
full_names
array to keep the concatenated names.
If you define the callback as a separate function, it would become a bit more readable.
let full = employees.map(get_full_name);
function get_full_name(emp){
return emp["first_name"] + ' ' + emp["last_name"]
}
Wrapping It Up
In this quick tutorial, you saw how to use JavaScript map
method for Array manipulation. Have you used it for Array manipulation ? How was your experience ? Do let us know in the comments below.