Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 283
Sumit Aggarwal Avatar asked Feb 12 '16 07:02

Sumit Aggarwal


People also ask

Can I break array map?

javascript break out of map // You cannot break out of `Array.

How do I remove an item from an array in maps?

Map.delete() Method in JavaScript The Map. delete() method in JavaScript is used to delete the specified element among all the elements which are present in the map.

How do I stop a map from looping?

To break a map() loop in React: Call the slice() method on the array to get a portion of the array. Call the map() method on the portion of the array.


1 Answers

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.

like image 93
Z4- Avatar answered Oct 04 '22 22:10

Z4-