Sometimes you may need to take an array and apply some logic to its elements so that you get a new array with updated values.
There are multiple ways to achieve this requirement. You may want to do it by creating an empty array, then using .forEach()
or a simple .for()
to meet your requirement.
Instead of manually iterating over the array using a loop, you can simply use the built-in Array.map()
method.
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(ele, index, array){ }, this);
The callback function()
is called on each array element, and the map()
method always passes the current element
, the index
of the current element, and the whole array
object to it.
The this
argument will be used inside the callback function. By default, its value is undefined
.
let users = [
{firstName : "ram", lastName: "lakshman"},
{firstName : "our", lastName: "techvillage"},
{firstName : "java", lastName: "script"}
];
let userFullnames = users.map(function(element){
return `${element.firstName} ${element.lastName}`;
})
Output:
["ram lakshman", "our techvillage", "java script"]
0 Comments