javascript map function returned undefined

Viewed 48
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.

3 Answers

.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.

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);

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