Akshat Jiwan Sharma Akshat Jiwan Sharma - 5 months ago 43
Javascript Question

Why does javascript map function return undefined?

My code

var arr = ['a','b',1];
var results = arr.map(function(item){
if(typeof item ==='string'){return item;}

This gives the following results


I don't want undefined in the results array.How can I do it?


You aren't returning anything in the case that the item is not a string. In that case, the function returns undefined, what you are seeing in the result.

The map function is used to map one value to another, but it looks you actually want to filter the array, which a map function is not suitable for.

What you actually want is a filter function. It takes a function that returns true or false based on whether you want the item in the resulting array or not.

var arr = ['a','b',1];
var results = arr.filter(function(item){
    return typeof item ==='string';