Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript map returning undefined for some elements [duplicate]

Given the following array of member data, I'm to return an array of memberID's for members whose membership status not current.

Here's the member data:

var members = [
  {
    firstName: 'Howard',
    lastName: 'Lee',
    membershipIsCurrent: true,
    MemberID: 235
  },
  {
    firstName: 'James',
    lastName: 'Icharis',
    membershipIsCurrent: false,
    MemberID: 236
  },
  {
    firstName: 'Thomas',
    lastName: 'Cronquist',
    membershipIsCurrent: true,
    MemberID: 237
  },
  {
    firstName: 'Philip',
    lastName: 'Grover',
    membershipIsCurrent: false,
    MemberID: 238
  },
  {
    firstName: 'Eric',
    lastName: 'Broadstone',
    membershipIsCurrent: true,
    MemberID: 239
  },
  {
    firstName: 'Hunter',
    lastName: 'Gonzales',
    membershipIsCurrent: true,
    MemberID: 240
  }];

Here is my code to grab that data:

function lapsedIDs (array ) {
  return array.map( function ( member ) {
    if ( member.membershipIsCurrent === false ) {
      return member.MemberID;
    }
  });
}

lapsedIDs(members);

Here is the result. I don't understand why it's returning undefined for each member whose membership has NOT lapsed. Any pointers??

[ undefined, 236, undefined, 238, undefined, undefined ]
like image 604
208_man Avatar asked Dec 14 '22 19:12

208_man


1 Answers

map() will create a new element for every existing one in the original array.

If you don't return something for all conditions a function automatically returns undefined which is what you are seeing

You could filter() first to remove the unwanted items and then map()

 return array.map( function ( member ) {
    return member.membershipIsCurrent
  }).map(function(member){
     return member.MemberID;
  });
like image 63
charlietfl Avatar answered Dec 17 '22 22:12

charlietfl