Sumit Aggarwal
Sumit Aggarwal

Reputation: 841

How I can skip the element of array .map?

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 give the result like this:

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

I want to skip the undefined elements in the array.

Upvotes: 18

Views: 52640

Answers (5)

Yoel
Yoel

Reputation: 7985

you can use flatMap

The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1, but slightly more efficient than calling those two methods separately.

var userids = userbody.contacts.flatMap((obj)=>{
  if((obj.iAccepted=='true')&&(obj.contactAccepted=='true')) {
    return obj.userID 
  } 
  else{
    return[];
  }

});

Upvotes: 1

Derek Wang
Derek Wang

Reputation: 10204

You can use Array.reduce function to implement Array.map and Array.filter process in one function as follows.

const userIds = userbody.contacts.filter((acc, cur) => {
  if((obj.iAccepted == 'true') && (obj.contactAccepted == 'true')) {
    acc.push(obj.userID);
  }
  return acc;
}, []);
console.log(userIds);

Upvotes: 1

William
William

Reputation: 4588

Not sure if this is what you're 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/

Upvotes: -1

Shanoor
Shanoor

Reputation: 13692

You can filter out the false values:

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

Or, if you can't use arrow functions:

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

Upvotes: 0

Z4-
Z4-

Reputation: 1899

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

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

The filter part takes out all unnecessary elements, then map converts the rest to the way you want.

Upvotes: 50

Related Questions