Home > Mobile >  How to filter objects based on given condition in JavaScript?
How to filter objects based on given condition in JavaScript?

Time:02-13

I'm new to this community and just started programming I couldn't find anything about this topic can anyone please solve this. I need to filter names who's each points in array above 75. i have tried this and unable iterate over an array.

const candidatesList = [{'name':'Blake Hodges', 'points':[76,98,88,84]},{'name':'James Anderson', 'points':[0,98,12,13]}]

const arrayOfSelecetedCandidates=[]
  for(let object of candidatesList){
      if (candidatesList.every(candidatesList.points>75)){
         arrayOfSelecetedCandidates.push(candidatesList.name)
      }
  }
  console.log(arrayOfSelecetedCandidates);```

output like this:-
```['Blake Hodges']```

CodePudding user response:

Maybe you want this?

const candidatesList = [{'name':'Blake Hodges', 'points':[76,98,88,84]},{'name':'James Anderson', 'points':[0,98,12,13]}]

const arrayOfSelecetedCandidates=[]
  for(let object of candidatesList){
      if (object.points.every(i=>i>75))
         arrayOfSelecetedCandidates.push(object.name)
  }
  console.log(arrayOfSelecetedCandidates);

But as @Dai pointed out filter is always better if you want to test an array and return item that pass the test:

const candidatesList = [{'name':'Blake Hodges', 'points':[76,98,88,84]},{'name':'James Anderson', 'points':[0,98,12,13]}]

const arrayOfSelecetedCandidates=candidatesList.filter(i=>i.points.every(y=>y>75))
console.log(arrayOfSelecetedCandidates)

CodePudding user response:

You can achieve this by using Array.filter() method along with Array.every() to test whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

Working Demo :

const candidatesList = [{
    'name': 'Blake Hodges',
    'points': [76, 98, 88, 84]
}, {
    'name': 'James Anderson',
    'points': [0, 98, 12, 13]
}];

let res = candidatesList.filter((obj) => {
    return obj.points.every((item) => item > 75)
});

console.log(res);

  • Related