AppDividend
Latest Code Tutorials

Javascript Array Map Example | Array.prototype.map() Tutorial

0

Javascript Array Map Example | Array.prototype.map() Tutorial. The map() method creates the new array with the results of a provided function on every item in the calling array. The map() function calls the provided callback function once for each element in the array and in order and constructs the new array from the results. The Javascript array map() function is a pure function, and it does not modify the existing array instead it will return a new array.

Javascript Array Map Example

The map() method calls the provided function once for each element in an array, in order. The callback function is invoked with the following three arguments: the value of the element, the index of the element, and the Array object that is being traversed. The syntax is following.

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

The currentValue is a required parameter, and it is the current value of the element.

The index is an optional parameter, and it is the index of the current element.

The arr is an optional parameter which is the array object the current element belongs to.

Under the hood, the map function passes three arguments to your callback:

  1. The current item in the array
  2. The array index of the current item
  3. The entire array you called map on

If existing elements of an array are changed based on the logic, then their value as passed to callback be the value at the time map visits them.

Let us take an example by creating a file called app.js. Add the following code.

let numbers = [1, 2, 3];
let squares = numbers.map(item => item * item);

console.log(squares);

So, in the above example, the numbers array will be traversed and perform the square operation to each item of an array and return a new array with those items filled with. So the new array will be the squared items of each element.

Javascript Array Map Example | Array.prototype.map() Tutorial

#Using the map to reformat objects in an array

We can also use the map method to format the object in the given array like the following code.

// app.js

let gtu = [
    {enrollnumber: 18, name: 'Shree'}, 
    {enrollnumber: 21, name: 'Krunal'},
    {enrollnumber: 22, name: 'Rushikesh'}
];

let mappedArrayObj = gtu.map(obj => { 
   let newObj = {};
   newObj[obj.enrollnumber] = obj.name;
   return newObj;
});

console.log(mappedArrayObj);

So, in the above example, we have taken an array of objects. The object has two properties. So we have reformated the new object by creating the first object’s value as a key and second object’s value as a value.

So the result will be like this.

Javascript Array map() tutorial

#Access index of an array in a map() method

We can access the index by passing the second argument to the callback function.

// app.js

let no = [1, 3, 4, 5];

no.map((item, i) => console.log(i));

Now, you can access all the index of the current item being iterated.

We can define the function separately and pass the value to that function and get the result.

// app.js

let no = [1, 3, 4, 5];

const square = (x) => {
    return x*x;
}

let newArray = no.map((item, i) => square(item));

console.log(newArray);

In the above example, we have defined the function separately and pass the current item to that function, and that function returns the square of that item.

Javascript Array map() method is a pure function, and if you have any experience in Redux, then it is familiar to you. It will always return a new array which is the principal of immutability.

If we need to transform the whole array into a new array, then map() is a beneficial method in Javascript.

You should use the filter() method rather than map unless you want to mutate the elements in an array, in addition to filtering.

#Map, For loop, and forEach function

Let’s take three examples which are the same but implementation will be different using Javascript map() method, Javascript for loop, and Javascript forEach() function.

Let’s make another array using the for loop.

// app.js

let strangerThings = [{
  name: 'Dustin',
  age: 13
}, {
  name: 'Mike',
  age: 12
  },
  {
    name: 'Eleven',
    age: 11
  }];

let characters = [];  

for (let i = 0, max = strangerThings.length; i < max; i += 1) {
  characters.push(strangerThings[i].name);
}
console.log(characters);

See the following output.

➜  es git:(master) ✗ node app
[ 'Dustin', 'Mike', 'Eleven' ]
➜  es git:(master) ✗

In the above example, we are iterating each element one by one and add the names to the new array.

Now, let’s see that example using Javascript forEach function.

// app.js

let strangerThings = [{
  name: 'Dustin',
  age: 13
}, {
  name: 'Mike',
  age: 12
},
{
  name: 'Eleven',
  age: 11
}];

let characters = [];

strangerThings.forEach(function (role) {
  characters.push(role.name);
});

See the following output.

➜  es git:(master) ✗ node app
[ 'Dustin', 'Mike', 'Eleven' ]
➜  es git:(master) ✗

Array forEach function loop item one by one and add the element to the new array.

Now, let’s use the Javascript map() function.

let strangerThings = [{
  name: 'Dustin',
  age: 13
}, {
  name: 'Mike',
  age: 12
},
{
  name: 'Eleven',
  age: 11
}];

let characters = strangerThings.map(function (character, index, array) {
  return character.name; 
});
console.log(characters);

The map() function returns a new array and it is a pure function. So, it does not modify the old array.

See the output.

➜  es git:(master) ✗ node app
[ 'Dustin', 'Mike', 'Eleven' ]
➜  es git:(master) ✗

There are a few important differences between the two approaches:

  1. Using the map() function, you don’t have to manage the state of for loop yourself.
  2. You can operate on the element directly, rather than having to index into the array.
  3. You don’t have to create a new array and push into it. The map() returns the finished product all in one go, so we can simply assign the return value to a new variable.
  4. You do have to remember to include a return statement in your callback. If you don’t, you’ll get a new array filled with undefined. 

Turns out, all of the functions we’ll look at today share these characteristics.

The fact that we don’t have to manually manage the state of the loop makes our code more simpler and more maintainable. We can operate directly on the item instead of having to index into an array makes things more readable. 

Using a forEach function solves both of these problems for us. But Javascript map() function  still has at least two distinct advantages:

  1. The forEach returns undefined, so it doesn’t chain with other Javascript array methods. The map() function returns the array, so you can chain it with the other array methods.
  2. The map() returns an array with the finished product, rather than requiring us to mutate the array inside a loop. 

Keeping the number of places where you modify state to an absolute minimum is an important tenet of functional programming. It makes for safer and more intelligible code.

If you want to filter and map the array values using the one function then you should use the Array.reduce() method to accomplish the task.

#Map An Array of Objects and Return new Object With New Keys

You can iterate an array of objects and then change the key of that object and return an array of objects with a new key.

See the following code example.

// app.js

let strangerThings = [{
  name: 'Dustin',
  age: 13
}, {
  name: 'Mike',
  age: 12
},
{
  name: 'Eleven',
  age: 11
}];

let characters = strangerThings.map(data => ({
  actual: data.name,
  main: data.age
}));
console.log(characters);

In the above example, we have an array of objects called strangerThings and its object keys are name and age.

Now, we need to change the key name and values and put the actual and main.

So, we have used the map() function and change the keys and return the new array characters which have two different keys. See the following output.

➜  es git:(master) ✗ node app
[ { actual: 'Dustin', main: 13 },
  { actual: 'Mike', main: 12 },
  { actual: 'Eleven', main: 11 } ]
➜  es git:(master) ✗

Finally, Javascript Array Map Example | Array.prototype.map() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.