JavaScript Array Map method

JavaScript Array Map method

All you need to know about array.map() method

  • The map() method creates a new array with the results of calling a function for every array element.

  • The map() method calls the provided function once for each element in an array in order.

    Syntax

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

  • Argument -> Description

  • currentValue -> Required the value of the current element

  • index (optional) -> The array index of the current element.

  • arr (optional) -> The array object the current element belongs to

    const oldArr = ['laraib', 'nehal']
    
    const newArr = oldArr.map(function(cval)){
    
    return val
    
    });
    
    console.log(newArr);
    

Using a map to reformat objects in an array

The following code takes an array of objects and creates a new array containing the newly reformatted objects.

const kvArray = [
  { key: 1, value: 10 },
  { key: 2, value: 20 },
  { key: 3, value: 30 },
];

const reformattedArray = kvArray.map(({ key, value }) => ({ [key]: value }));

console.log(reformattedArray); // [{ 1: 10 }, { 2: 20 }, { 3: 30 }]
console.log(kvArray);
// [
//   { key: 1, value: 10 },
//   { key: 2, value: 20 },
//   { key: 3, value: 30 }
// ]

Using parseInt() with map()

It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviours.

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

While one might expect [1, 2, 3], the actual result is [1, NaN, NaN].

parseInt is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, Array.prototype.map passes 3 arguments:

  • the element

  • the index

  • the array

The third argument is ignored by parseInt—but not the second one! This is the source of possible confusion.

Here is a concise example of the iteration steps:

// parseInt(string, radix) -> map(parseInt(value, index))
/* first iteration  (index is 0): */ parseInt("1", 0); // 1
/* second iteration (index is 1): */ parseInt("2", 1); // NaN
/* third iteration  (index is 2): */ parseInt("3", 2); // NaN

Then let's talk about solutions.

const returnInt = (element) => parseInt(element, 10);

["1", "2", "3"].map(returnInt); // [1, 2, 3]
// Actual result is an array of numbers (as expected)

// Same as above, but using the concise arrow function syntax
["1", "2", "3"].map((str) => parseInt(str)); // [1, 2, 3]

// A simpler way to achieve the above, while avoiding the "gotcha":
["1", "2", "3"].map(Number); // [1, 2, 3]

// But unlike parseInt(), Number() will also return a float or (resolved) exponential notation:
["1.1", "2.2e2", "3e300"].map(Number); // [1.1, 220, 3e+300]

// For comparison, if we use parseInt() on the array above:
["1.1", "2.2e2", "3e300"].map((str) => parseInt(str)); // [1, 2, 3]

The mapped array contains undefined

When undefined or nothing is returned:

const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.map((num, index) => {
  if (index < 3) {
    return num;
  }
});

// index goes from 0, so the filterNumbers are 1,2,3 and undefined.
// filteredNumbers is [1, 2, 3, undefined]
// numbers is still [1, 2, 3, 4]