Home > Software engineering >  javascript map function returned undefined
javascript map function returned undefined

Time:06-21

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

// filteredNumbers is [1, 2, 3, undefined]

According to my understanding callback function should return all numbers of array if their index is less than 3 so it should return 1,2,3 and stop after that and number 4 can not be returned as if condition says index should be less than 3. I am wondering why it returned undefined for index 3 number.

CodePudding user response:

.map is an isomorphism and preserves the length of the given array.

So if the callback function does not return anything, the index will be undefined.

CodePudding user response:

You want to user a filter function instead if you need to filter array elements that meet a certain condition.

const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.filter((_, index) => index < 3);

console.log(filteredNumbers);

CodePudding user response:

If you want just to get the first 3 items in the array, I recommend using slice.

const numbers = [1, 2, 3, 4];
console.log(numbers.slice(0, 3));

Second solution is use filter instead of map.

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

console.log(filteredNumbers)

  • Related