Complete guide to Javascript .map() function


Javascript map() function can applies a function to each element in an array and returns a copy of the original array with modified values (if any).

Syntax

const newArray = oldArray.map(function(elementValue, index, array) {
  // Do stuff with elmentValue (index and array are optional)
});

Parameteres

  • newArray – the new array that is returned
  • oldArray – the old array being operated on. This array will not be changed
  • elementValue – the current value being processed
  • index – the current index of the value being processed
  • array – the original array

Doubling an array using .map() function

var numbers = [1,2,3,4,5];
var newNumbers = numbers.map((element)=>{
return element*2;
});
var oneLineArray = numbers.map(element=>element*3);
console.log(newNumbers);
//Output: [2,4,6,8,10]
console.log(oneLineArray);
//Output: [3,6,9,12,15]

Using .map() function along with .revers() function

.reverse() function can reverse an array.

var numbers = [1,2,3,4,5];
var newNumbers = numbers.reverse().map((element)=>{
return element*2;
});
var oneLineArray = numbers.reverse().map(element=>element*3);
console.log(newNumbers);
//Output: [10,8,6,4,2]
console.log(oneLineArray);
//Output: [15,12,9,6,3]

Using .map() function to convert an Object into an array

Javascript map() only work on array. We can convert an object into an array and conduct map() operation into it. We can use Object.keys(), Object.values(), and Object.entries() all return an array, meaning that map() can easily be chained to each method:

const obj = {
a:1,
b:2,
c:3
};

const values = Object.values(obj).map(num=>num*2);
console.log(values);
//output: [2,4,6]
const keys = Object.keys(obj).map(key=>key.concat('a'));
console.log(keys);
//output: ["aa","ba","ca"]
const entries = Object.entries(obj);
console.log(entries);
//output: [["a",1],["b",2],["c",3]]