The map() method can be used to modify all elements of an array. Below, I have a function that will take an array of sales prices, and mark them up by 10% to account for sales tax. On line 3, if I return the item without the parseFloat function, it converts all the elements in the array to a string, so I use the parseFloat function (to return a number with decimals) and the toFixed() method round to two decimal places.
function addTax(item) { const taxRate = .10; return parseFloat((item * (1 + taxRate)).toFixed(2)); } const sales=[1,20,25,5,30,100]; const output = sales.map(addTax); console.log(output); // output = [ 1.1, 22, 27.5, 5.5, 33, 110 ]
Next, I will modify an array of objects using the map() method. The addPrefix function will look at the sex of the item. If the sex is male, it will add “Mr. ” to the name, and if the sex is female, it will add “Ms. ” to the name.
const names = [ { name: 'Jones', sex: 'male' },{ name: 'Smith', sex: 'female' },{ name: 'Tanaka', sex: 'male'} ]; function addPrefix(item) { if(item.sex === 'male') { item.name = "Mr. " + item.name; } else if (item.sex === 'female') { item.name = "Ms. " + item.name; } return item; } const output = names.map(addPrefix); console.log(output); // output = [ { name: 'Mr. Jones', sex: 'male' }, { name: 'Ms. Smith', sex: 'female' }, { name: 'Mr. Tanaka', sex: 'male' } ]
Leave a Reply