HomeToolsAbout

map

What is it

Creates a new array populated with the results of calling a provided function on every element in the calling array.

  • Map returns a deep copy (new memory)
// 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]

When not to use .map()

Since map builds a new array, using it when you aren't further using the returned array is an anti-pattern

  • use forEach or for...of instead

Illustration

Using 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 } // ];

Edge Cases

Mapped Array contains undefined

When undefined or nothing is pushed to the array, the position in the array will be occupied with undefined

  • If you want to delete the element instead, chain a filter() method, or use the flatMap() method and return an empty array to signify deletion
AboutContact