HomeAbout

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)
const original = [1, 4, 9, 16]; const newArr = array1.map((x) => x * 2); console.log(original); // [1, 4, 9, 16]; console.log(newArr); // [2, 8, 18, 32];

Params

map((currentValue, index, array) => { ... } )

When not to use .map()

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

  • use forEach or for...of instead when you don't need a new array.

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(originalArr); // [ // { key: 1, value: 10 }, // { key: 2, value: 20 }, // { key: 3, value: 30 } // ]; console.log(newArr); // [ // { 1: 10 }, // { 2: 20 }, // { 3: 30 } // ];

Removing Elements while Mapping

When you return nothing ("returning a void") while mapping, resulting array will contain undefined in the position.

const arr = [1, 2, 3, 4, 5]; // function to filter out even numbers and only return odds const result = arr.map(item => { if (item % 2 === 0) { return; // returns `undefined` in the position } return item; }); console.log(result); // [1, undefined, 3, undefined, 5]

If you want to delete the element while mapping:

  • chain a filter() method after the map to explicitly remove based on a passed condition; OR
  • use the flatMap() method and return an empty array to signify deletion.

Using flatMap

const arr = [1, 2, 3, 4, 5]; // flatMap const result = arr.flatMap((item) => { // swap condition and return item here for parity with filter if (item % 2 === 0) { return []; // removes element } return item; // returns element }); console.log(result); // [1, 3, 5]

Using filter (true is included)

const result = arr.filter(item => (item % 2 === 1)).map(item => item); console.log(result); // [1, 3, 5]

flatMap

flatMap can be used as a way to add and remove items (modify the number of items) during a map.

flatMap maps many-items-to-many-items (by handling each input item separately), rather than always one-to-one.

  • In this sense, works like an opposite of a filter.

Return a 1-element array to keep the item, a multiple-element array to add items, or a 0-element array to remove the item.

// Let's say we want to remove all the negative numbers // and split the odd numbers into an even number and a 1 const a = [5, 4, -3, 20, 17, -33, -4, 18]; // |\ \ x | | \ x x | // [4,1, 4, 20, 16, 1, 18] const result = a.flatMap((n) => { if (n < 0) { return []; // remove } return n % 2 === 0 ? [n] : [n - 1, 1]; // add or keep }); console.log(result); // [4, 1, 4, 20, 16, 1, 18]
AboutContact