59. Array Transformation: The .map() Method
.map() is one of the most powerful high-order array methods. It calls a function for every element in the array and returns a new array containing the results of that function.
This is essential for transforming data from one format to another.
Example: Converting Prices
Imagine we have prices in Euros and need to convert them to USD (assuming 1 EUR = 1.08 USD).
javascript const euroPrices = [100, 250, 450]; const exchangeRate = 1.08;
const usdPrices = euroPrices.map(price => { return price * exchangeRate; });
console.log(euroPrices); // [100, 250, 450] (Original array is unchanged) console.log(usdPrices); // [108, 270, 486] (New array with transformed values)
Transforming Objects
If you have an array of simple objects, .map() is perfect for extracting a single property or formatting them.
javascript const users = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];
const names = users.map(user => user.name); console.log(names); // ['A', 'B']