Expert Use Cases for the Javascript Map() Method

Expert Use Cases for the Javascript Map() Method

The javascript map() method is commonly used on arrays. It accepts a function as a parameter, applies the function to each array element, and returns the modified elements in a new array.

The map() method never modifies the input array's elements and always returns a new array.

map calls a provided callbackFn function once for each element in an array, in order, and constructs a new array from the results. callbackFn is invoked only for indexes of the array which have assigned values (including undefined). --- mdn web docs

syntax:

array.map(function(currentValue, index, arr), thisArg)

Map accepts two parameters

  • The first parameter is a callback function that is applied to each element of an array. This parameter is required.
  • The second parameter, thisArg is optional.

First Parameter

function(currentValue, index, arr)

Each element of the array are modified by this function. It takes in three parameters:

  • currentValue: It is a required parameter of the callbackfn and holds the value of the current array element being traversed.

  • index: Optional parameter. It is the current array element's index.

  • arr: Optional parameter. This is the input array being traversed.

Second parameter

thisArg

  • thisArg: is an optional parameter of the map() method. thisArg can be provided to change the inner .this of the callback function.

    thisArg refers to the method's execution context.

    If we don't specify the thisArg it points to the Window.

Return Value

map() returns a new array, containing elements modified by the callback function.

A quick look at the Javascript map() method in action:

const initialArray = [0,1,2,3,4];

//callback function
function doubleElement(x){
  return x*2;
}

//Pass callback func
const newArray = initialArray.map(doubleElement);

console.log(initialArray);  // [0,1,2,3,4]
console.log(newArray);   // [0,2,4,6,8]

The map() method is called on our input array, and the callback function doubleElement is used to modify each element of the array. A new array is returned.

Now let's look at some expert use cases of the map() method

1. Extracting object keys with map()

The map() method can be used to extract and modify the keys in an array of objects:

const originalArray = [
  {
 a: 1,
 b: 'first'
 },
  { a: 2, b: 'second' },
  { a: 3, b: 'third' },
];

const newArray = originalArray.map(object => object.b);

console.log(newArray); // ['first', 'second', 'third']

The callback function in this case takes in each object of the array and returns a new array of selected keys.

2. Use map() method to iterate through an object

Using the map() method, we can iterate over objects and change their values.

While map() does not work directly on objects. We can use the javascript Object.entries method in conjunction with the map() method to iterate over and modify the values of an object.

const object = {
    foo: '7',
    baz: 42 
}

const array = Object.entries(object);
console.log(array); // [["foo",7], ["bar",42]]

const newArray = array.map(([key, value])=> ["new"+key, value*2]);

console.log(newArray);

The first item in an object is the key, and the second item is the value, in our callback function, we use array destructuring to specify them.

All keys are updated, and values are doubled and returned as an array.

Note: use the javascript reduce method to convert our output array back to an object:

var obj = newArray.reduce(function(acc, cur, i) {
  acc[i] = cur;
  return acc;
}, {});
console.log(obj);

3. Using Built-in Functions and Objects in map

The map() method passes three arguments to its callback function (currentValue, index, arr). Only one argument (currentValue) is required by the callback function for our map() operation, while the others are optional.

We can pass JavaScript built-in functions and objects as an argument to our map() method.

[1, 2, 3].map(String);                   //['1', '2', '3']

["1", "2", "3"].map(Number);           //[1, 2, 3] 

[2,4,16,256].map(Math.sqrt);    //[1.4142135623730951, 2, 4, 16]


//Same thing as
[1,2,3].map(num=> String(num))          //['1', '2', '3']

["1","2","3"].map(num=> Number(num))      // [1, 2, 3]

[2,4,16,256].map(num=> Math.sqrt(num))     //[1.4142135623730951, 2, 4, 16]

What exactly is happening here?

  • Run map function on the numbers array

  • map() takes each item of the array and passes it to the built-in functions and objects used in our code.

  • A new array with transformed elements is returned.

4. Map Method for 2-dimensional Arrays

Using the map() method for a 2-dimensional array, this is an array with nested arrays.

const myArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

A map can be used to loop through this array, but it will only operate on the top-level array. The callback function will first access array [1, 2, 3], then array [4, 5, 6], and finally array [7, 8, 9].

The callback function receives an array as its first argument!

If we want to modify the values of the internal arrays, we can use a map inside our map:

const myArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

const newArray = myArray.map(value => value.map(number => number * 2));

console.log(newArray); // [[2, 4, 6], [8, 10, 12], [14, 16, 18]]

This is known as using a map within a map:

However, if you want to convert your two-dimensional array into a one-dimensional array of transformed values, map() will be ineffective. You should use the flatMap() function here.

flatMap() transforms a multidimensional array into a single-dimensional array of transformed values.

5. Render a List in React.js

When using the React library, you can also use map() to render an array list.

import React from ‘react’;
import ReactDOM from ‘react-dom’;

const numbers = [1,2,3,4,5];
const listItems = numbers.map( (number) =>
<li key={number}> {number} </li>
);

ReactDOM.render(
 <ul>{listItems}</ul>,
 document.getElementById('root')
);

Note the use of the key attribute inside the map to ensure react.js has a unique reference for the element from each loop iteration. If the key attribute is not specified, React library issues a warning message!

How not use map() method

  • Whenever nothing or undefined is returned

If there is no return value when using the map method, undefined is returned implicitly.

const fruitIds = ['apple', 'oragne', 'banana'];
fruitIds.map((id) => {
   document.getElementById(`fruit-${id}`).classList.add('active');
});

//[undefined, undefined, undefined]

In the above example, there are no serious consequences - there are only three items in the array so creating another array of three undefined values will not cause any problems.

The issue arises when we deal with large arrays of complex data. If we want to iterate over a large array using .map() without specifying a return value. Another array of equal size containing - undefined is returned by default.

As a result, we have redundant data.

Hence in cases where we are handling large datasets, we can use, for, for... of and more to solve this side-effect. map() should be used for mapping and return of new array.

Conclusion

We've taken a look at the syntax, parameters and usage of the map() method through practical examples and some expert use cases.

Further - we looked at when not to use the map method.

Learn More