Creates a new array
populated with the results of calling a provided function
on every element
in the calling array.
// full syntax map((currentValue, index, array) => { ... } ) // example const array1 = [1, 4, 9, 16]; const map1 = array1.map((x) => x * 2); console.log(map1); // new array [2, 8, 18, 32]; console.log(array1); // same array [1, 4, 9, 16]
.map()
Since map
builds a new array
, using it when you aren't further using the returned array is an anti-pattern
forEach
or for...of
insteadUsing map to re-format records in array
const originalArr = [ { key: 1, value: 10 }, { key: 2, value: 20 }, { key: 3, value: 30 }, ]; // reformat to map `key` and `value` fields together const newArr = originalArr.map(({ key, value }) => ( { [key]: value }) ); console.log(newArr); // [ // { 1: 10 }, // { 2: 20 }, // { 3: 30 } // ]; console.log(originalArr); // [ // { key: 1, value: 10 }, // { key: 2, value: 20 }, // { key: 3, value: 30 } // ];
undefined
When undefined
or nothing is pushed to the array, the position in the array will be occupied with undefined
filter()
method, or use the flatMap()
method and return an empty array to signify deletion