What Is It?
Use the map()
method to transform elements in an array.
Like filter()
, map returns a new array leaving the original array unchanged. However unlike filter it returns a new array with the same number of array elements.
const array = [ ... ]
const processedArray = array.map( item => /* Process item */ );
To transform an array’s items with map, you use a callback function to process and return the data you want.
When to Use It?
Say for example that you have an array of words you want to pluralize. Or you could use map to go through an array of temperatures, converting them from Celsius to Fahrenheit.
Perhaps you have an array of prices as numbers and you want to turn them into strings and put a dollar sign on the front of them.
Example
Turn an array of string numbers into actual numbers.
const strings = ['1','2','3','4','5'];
const numbers = strings.map( string => parseInt(string, 10));
console.log(numbers);
Example
Using map()
, turn the strings of an array into uppercased strings
const fruits = ['apple', 'pear', 'cherry'];
let capitalizedFruits = [];
fruits.forEach(fruit => {
let capitalizedFruit = fruit.toUpperCase();
capitalizedFruits.push(capitalizedFruit);
});
console.log(capitalizedFruits);
Solution:
const fruits = ['apple', 'pear', 'cherry'];
const capitalizedFruits = fruits.map( fruit => fruit.toUpperCase() );
console.log(capitalizedFruits);
Example
Correct the way the prices are being displayed, and make it a reusable feature
const prices = [5, 4.25, 6.4, 8.09, 3.20];
const priceToDollars = price => `$${price.toFixed(2)}`;
const displayPrices = prices.map( priceToDollars );
console.log(displayPrices);
Example
Create a new array of abbreviated week days.
const daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const abbreviatedDays = daysOfWeek.map( day => day.substring(0,3));
// Output: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]