skip to Main Content

I have an array of objects(data from BE) I need to filter by one specific value and return a list of the IDs of those objects.

This will return the whole object, so i could run in a for loop and append to a new array but seems lengthy.

const data = [{
    id: 1,
    name: "One",
    canAcceptRecruits: true
  },
  {
    id: 2,
    name: "Two",
    canAcceptRecruits: true
  },
  {
    id: 3,
    name: "Three",
    canAcceptRecruits: false
  }, {
    id: 50,
    name: "Fifty",
    canAcceptRecruits: true
  }
];

console.log(data.filter(x => x.canAcceptRecruits == true));

I know i can use a map or a reducer to perform the operation, but i was wondering if there is anything more succinct, nicer perhaps.

Thanks in advance

2

Answers


  1. Array.map seems like the best option.

    const ids = this.props.constants.divisions
      .filter((x) => x.canAcceptRecruits == true)
      .map(x => x.id);
    
    Login or Signup to reply.
  2. We can use Array.forEach and loop only once. might be alittle faster than filter + map

    const data = [{ id: 1, name: "One", canAcceptRecruits: true  }, {  id: 2, name: "Two", canAcceptRecruits: true  },  {  id: 3, name: "Three", canAcceptRecruits: false  }, { id: 50, name: "Fifty", canAcceptRecruits: true }]
    
    let result = [];
    
    data.forEach(x => {if(x.canAcceptRecruits) result.push(x.id)})
    console.log(result)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search