29
loading...
This website collects cookies to deliver better user experience
array.map()
method from freeCodeCamp.map()
method? The map()
method allows you to iterate over an array and modify it using a callback function on each element and returning a new array, with transformed elements. This way you get an entirely new array and an untouched original array. for loop
. Like the example below.let numbers = [1, 2, 3, 4]
for(let i = 0; i < numbers.length; i++{
console.log(numbers[i] * 5);
}
//output: [5, 10, 15, 20]
map()
method.let numbers = [1, 2, 3, 4]
let newNumbers = numbers.map(function(element){
return element * 5;
}
console.log(newNumbers);
//output: [5, 10, 15, 20]
callback function
is called on each element
(current value) of the array and multiply each of the element by 5 and returns a new element
(new value) and adds it into the new array let newNumbers
.map()
method is:arr.map(function callbackFn(element, index, array))
function callbackFn()
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
of the object.make
, model
, and year
of cars. let cars = [
{make: "Lexus", model: "IS 250", year: "2014"},
{make: "Honda", model: "Accord", year: "2020"},
{make: "Toyota", model: "Camry", year: "2012"},
{make: "Tesla", model: "Model S", year: "2017"}
]
make
and model
. Well, we can do that by using map()
method, process the current element through the function
, and return the element's property value to add to the new array.let carsArr = cars.map(function(element){
return `${element.make} ${element.model}`
})
console.log(carsArr)
//output: ["Lexus IS 250", "Honda Accord", "Toyota Camry", "Tesla Model S"]
callback function
on each element of cars
and every time the function is executed, the return values, which in this case are make
and model
are added into carsArr
. Now when we console.log(carsArr)
we get the following output on our console. ["Lexus IS 250", "Honda Accord", "Toyota Camry", "Tesla Model S"]
.map()
method is beneficial when you want to iterate through an array or arrays of objects, apply changes to its elements
and have it return a new array.