If you use .map function and add some conditional statements in the callback function it may return undefined. Here is a simple example where .map function returns undefined.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const subjects = [ "Computer Science", "Computer Fundamentals", "Physics", "Algebra" ]; const computerSubjects = subjects.map((subject)=>{ if(subject.includes("Computer")){ return subject; } }); console.log(computerSubjects); // output : ["Computer Science", "Computer Fundamentals", undefined, undefined] |
Using filter instead of map function
In most cases where you are using a conditional statement inside the map, you can fix it by just using .filter function. Check the example below, you can just replace .map with .filter to fix the undefined issue.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const subjects = [ "Computer Science", "Computer Fundamentals", "Physics", "Algebra" ]; const computerSubjects = subjects.filter((subject)=>{ if(subject.includes("Computer")){ return subject; } }); console.log(computerSubjects); // output : ["Computer Science", "Computer Fundamentals"] |
In some situations, you may want to use .map function not filter because of some calculations. Let’s say you want to map through all the elements and if the element meets a condition you want to perform some calculations. Check the example below where we have to return a modified element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const numbers = [22,33,44,55,11,23,5,6]; const modifiedNumbers = numbers.map((number)=>{ if(number>=18){ return number*2; } }); console.log(modifiedNumbers); // output : [44, 66, 88, 110, undefined, 46, undefined, undefined] |
Getting rid of falsy values with filter method
Now, you can’t replace .map with .filter to get your desired results because the filter method doesn’t return a modified element. In this case, to get rid of undefined from the output use filter at the end of map function with Boolean argument. Check the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const numbers = [22,33,44,55,11,23,5,6]; const modifiedNumbers = numbers.map((number)=>{ if(number>=18){ return number*2; } }).filter(Boolean); //filters falsy values console.log(modifiedNumbers); // output : Array [44, 66, 88, 110, 46] |
In the above example, we are returning a modified element from the .map function and at the end of the map, all the falsy values are filtered with the .filter method.
Conclusion
You can either use the filter function instead of the map function to get rid of undefined values, or you can filter all the falsy values with the help of the filter method after the map function.