The map() method of an array creates a new array with the results of calling a function on every element in the array.
const numbers = [2, 4, 6, 8];
const numbersSquared = numbers.map(x => x * 2);
console.log(numbersSquared);
// [4, 8, 12, 16]
// common, more-advanced example
// in an array of objects, add several fields in a child object of the object
const SUVs = [
{"name": "Explorer",
"costs": {
"price": 49000,
"weightTax": 1400,
"gasTax": 2000
}
},
{"name": "Escalade",
"costs": {
"price": 60000,
"weightTax": 2200,
"gasTax": 1400
}
},
{"name": "Tahoe",
"costs": {
"price": 55000,
"weightTax": 1700,
"gasTax": 1300
}
}
]
const SUVsTotalCost = SUVs.map((suv) => {
SUVTotal = {};
SUVTotal.name = suv.name;
totalCost = suv.costs.price + suv.costs.weightTax + suv.costs.gasTax;
SUVTotal.totalCost = totalCost.toLocaleString("en-US", {style:"currency", currency:"USD"});
return SUVTotal;
});
console.log(SUVsTotalCost);
[
{name: "Explorer", totalCost: "$52,400.00"},
{name: "Escalade", totalCost: "$63,600.00"},
{name: "Tahoe", totalCost: "$58,000.00"}
]
// common, more-advanced example
const cars = [
{"brand": "Ford", "color": "purple", "type": "minivan", "capacity": 7},
{"brand": "Chrysler", "color": "red", "type": "sports car", "capacity": 2},
{"brand": "Volkswagon", "color": "red", "type": "hatch back", "capacity": 4}
]
const carsUpperCase = cars.map((car) => car.brand.toUpperCase());
console.log(carsUpperCase);
// ["FORD", "CHRYSLER", "VOLKSWAGON"]