How can I skip an element of a .map array?

var userids = userbody.contacts.map(function(obj){ if((obj.iAccepted=='true')&&(obj.contactAccepted=='true')) { console.log(true); return obj.userID //return obj.userID } }); 

This will produce the following result:

['0', '35', '37', '30', '34', '36', '33', '32', undefined'332 ',' 328 ',' 337 ',' 333 ', undefined]

I want to skip undefined elements in an array.

+7
javascript
source share
3 answers

This is what is for Array.prototype.filter() . You need to do this in two steps.

 var userids = userbody.contacts .filter(contact => contact.iAccepted == 'true' && contact.contactAccepted == 'true') .map(contact => contact.userId); 

Part of the filter takes out all the unnecessary elements, then the map converts the rest the way you want.

+16
source share

Not sure if this is what you are looking for:

 var arr = [true,true,false,true,false]; var result = arr.map(function(val,ind,arr){ if(val === !false){ return val } }) console.log(result) // true, true , true 

https://jsfiddle.net/horonv8a/

0
source share

You can filter out false values:

 userids = userids.filter((i) => i); 

Or, if you cannot use the arrow functions:

 userids = userids.filter(function(i) { return i; }); 
0
source share

All Articles