Akshat Jiwan Sharma Akshat Jiwan Sharma - 1 year ago 148
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?

Answer Source

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';  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download