Home > Blockchain >  JavaScript flatMap() method logging NaN when action is performed on element
JavaScript flatMap() method logging NaN when action is performed on element

Time:10-22

Alright, this is a very basic question, but I'm not seeing the fix here. I want to flatten an array that has one layer of depth and at the same time multiply each element by 2. However, when I run flat map on arr1 the console is returning NaN instead of an array of 5 elements with each element being multiplied by 2. Code example below:

const arr1 = [ [2,5] , [5,10,15] ];

const arr2 = arr1.flatMap((el) => el * 2);

console.log(arr2);

Expected // [4, 10, 10, 20, 30]

Actual // [Nan, Nan]

If I run the flatMap without the multiplication I get the array with each element but it's only once I try to mulitply each value that I get the two NaN. What am I missing?

const arr3 = arr1.flatMap((el) => el); console.log(arr3);

Actaul // [2,5,5,10,15];

CodePudding user response:

const arr1 = [ [2,5] , [5,10,15] ];

var flattened = arr1.reduce(function(a, b) {
  return a.concat(b);
});
console.log(flattened)
const arr2 = flattened.flatMap((el) => el * 2);
console.log(arr2)

If you have nested array then you have to first flatten it then apply flatMap.Please read about how flatMap works.

CodePudding user response:

The el within your .flatMap() callback represents each of your elements in your array, which in your case will firstly be [2,5] and then on the next iteration will be [5,10,15]. Trying to multiply an array using el*2 will give you back NaN. Instead, what .flatMap() does is if you return an array from the callback, it will take all the elements from within that array and join it into the final resulting array. With this in mind, you can make your callback return an array of mapped/multiplied numbers, which then are all joined together in a final resulting array by .flatMap():

const arr1 = [ [2,5] , [5,10,15] ];
const arr2 = arr1.flatMap(inner => inner.map(el => el* 2));
console.log(arr2); // [4, 10, 10, 20, 30]

  • Related