The JavaScript .map method
Anatomy
[1, 2, 3] // An array (or any type)
.map( // method name
item, // single array element
index, // current elemet index
() => {} // function to be sequentially applied to each element (must return a result)
)
Basic examples
const integers = [1, 2, 3, 4, 5].map((item) => item * 2)
// [2, 4, 6, 8, 10]
const strings = ["one", "two", "three"].map((item, index) => `${index + 1} ${item}`)
// ["1 one", "2 two", "3 three"]
const mixedTypes = [undefined, null, "foo", 123, NaN, Symbol].map((item) => typeof item)
// ["undefined", "object", "string", "number", "number", "function"]
With expressions
[1, 2, 3, 4].map((item) => {
const evenOrOdd = item % 2 > 0 ? "odd" : "even"
console.log(`${item} is ${evenOrOdd}`)
return evenOrOdd
})
// 1 is odd
// 2 is even
// 3 is odd
// 4 is even
// ["odd", "even", "odd", "even"]