In Javascript, iterating over datasets is done traditionally using the For loop. Later ES6 came with other variance of the For loop i.e ForEach loop. In this tutorial, we are going to look at the traditional For loop and juxtapose it with the new .map() method.

According to MDN Documentation,

The .map() method creates a new array with the results of calling a provided function on every element in the calling array.

Syntax


var new_array = arr.map(function callback(currentValue[, index[,array]])) {
// Return element for new _array
}[, thisArg]

Basically, the .map() method when used on a dataset creates a new array by executing a callback function on each of the element of the initial array. This means we have 2 arrays of the dataset: the original array and the simplified array.

To demonstrate this, assuming we have an array of numbers and we need to multiply each element of the array by 2 and return the new array. We can achieve this in many ways.

 For Loop


let numArray = [10, 20, 30, 40];
let newNumArray = [];
for (var i=0; i<numArray.length; i++) {
   newNumArray.push(numArray[i] * 2);
}
console.log(newNumArray); // [20,40,60,80]

  .map()


let numArray = [10, 20, 30, 40];
let newNumArray = numArray.map ( num => num * 2);
console.log(newNumArray); // [20, 40, 60, 80]

Notice how the same result was achieved with a fewer number of lines.
In our daily programming activities, we will find the .map() method very useful and handy. We will now look at some of the ways we can use it.

1. Calling a function on each item in an Array.

As stated earlier, the .map() method accepts a callback function as one of its arguments, it is a required parameter which can be used to modify each element in the array. Here is an example;


let items = ['book', 'pencil', 'phone'];
let newItems = items.map( item => item += 's');
console.log(newItems) // [‘books’, ‘pencils’, ‘phones’]

Here we were able to call functions that add ‘s’ to all the items in the array.

2. Rendering a List in React Library.

Some JavaScript libraries like React uses .map() method to render items in a list in the DOM.


import React from 'react';
import ReactDOM from 'react-dom';

const tags: ['tag1','tag2', 'tag3']
renderTag () {
  return (
    { this.tags.map( tag =>
    <li>{ tag }</li>

)}
) } ReactDOM.render(, document.getElementById('root'));

Above is a component that renders a list of items in a ul tag in the DOM. The lists are rendered using the JavaScript .map() method.

3. Extracting values from an array of object.


const person = [
    { name: 'Deven', age: 30},
    { name: 'Joshua', age: 17},
    { name: 'Anthony', age: 42},
    { name: 'Malik', age: 20},
]

We want to extract the age of every person in the person array.


const person = [
    { name: 'Deven', age: 30},
    { name: 'Joshua', age: 17},
    { name: 'Anthony', age: 42},
    { name: 'Malik', age: 20},
]
const ages = person.map( person => person.age)
console.log(ages); // [30, 17, 42, 20]

4. Apply callback on only certain elements in an array.

Say we have an array of numbers and we need to find the square root of all numbers divisible by 5 within the array.


const numArray = [25, 125, 32, 49];
const sqrts = numArray.map( (num) => {
  return num % 5 === 0 ? Math.sqrt(num): num
 } );
console.log(sqrts); // [5, 11.180339887498949, 32, 49]

Here we were able to use the ternary operator to check which of the numbers in the array is divisible by 5, then we apply the callback function to return an array of the square root of the truthy elements and the false ones as it is.

5. Chain with .filter() method.

In some rare cases, we chain the map and filter methods to achieve some cool things. These two methods can be applied together to an array seamlessly. Say we have an array of several numbers.


const numArray = [5, 4, 7, 8, 19, 16, 13, 11, 10, 'boy', 'cool', 'filter'];
const newArray = numArray.filter ( element => {
    return Number.isInteger(element);
}).map( num => {
    return num * 10
});
console.log(newArray); // [50, 40, 70, 80, 190, 160, 130, 110, 100]

The filter method was used to filter the numArray and then return an array of only integers. Then we use the map method to multiply each element of the new array by 10.

6. Converting String to Array.

We all know that everything in JavaScript is an object and methods are just functions attached to these objects. Though .map() belong to the Array prototype, however, we can still utilize to convert a string to an array. We will simply use the .call() method which allows us to utilize the context of one object on another.


const string = 'Olabisi';
const newString = Array.prototype.map.call(string, eachletter => {
   return `${eachletter}`;
});
Console.log(newString) // ["O", "l", "a", "b", "i", "s", "i"]
// Check if newString is of type Array
Array.isArray(newString) // true

Conclusion

The JavaScript Array Map method is a method that can be used to simplify your code if used correctly. If you have other examples to show how you use the map method, please share them in the comment section.
Got any question or addition? Please leave a comment.