Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .map() returning without undefined

I have an object array and I want to create a new array with the ids only. Some records have id and others don't.

So I have something like:

var myMap = arr.map(function(e) {
    return e.id;
});

console.log(myMap); // [undefined, 2, 3, 4]

I'd like it to return just [2, 3, 4], if possible.

This JSFiddle should explain a little better: http://jsfiddle.net/dmathisen/Lnmj0w8k/

like image 891
dmathisen Avatar asked Dec 11 '22 03:12

dmathisen


1 Answers

It's not possible with just Array.map, you have to filter as well.

var myMap = arr.map(function(e) {
    return e.id;
}).filter(function(x) {
    return typeof x !== 'undefined';
});

As the ID's are always strings, you can do it like this as well

var myMap = arr.map(function(e) {
    return 'id' in e ? e.id : false;
}).filter(Boolean);

FIDDLE

like image 199
adeneo Avatar answered Dec 29 '22 09:12

adeneo