Home > Blockchain >  Js/React : Find ONLY the elements whitin an array that matches X condition to get X results
Js/React : Find ONLY the elements whitin an array that matches X condition to get X results

Time:01-13

Im getting different elements from an array that comes from the backend like so :

data = [{id: '1', collection: 32, isNew: true},{id: '5', collection: 22, isNew: false}, .... ]

The user is allowed to select in a massive way differents Ids, and edit them, and I need to show a different modal for each different cases : The conditions to show the differents modals are based on : If I select only the ones that has isNew = true, if I select only the ones with isNew= false, or if I select both Id cases isNew=false and isNew=true.

So far Ive tried this :

const getNewInfo = data.some(item => item.isNew)


if(getNewInfo) {
return this.explainNewInfo(true)
} else if(!getNewInfo) {
return this.explainNewInfo(false)
} else {
return this.explainNewInfo()
}

I also tried with the filter method and push to a new array, but it relies on the same logic at the end. For the first both cases, it works fine, but in the 3rd case, I cant get in, since whenever matches that isNew is true, it gets in there, and discard all the rest of posibilites. Each function that is being called on the if else, is a function that recives or not a parameter indicating if is necessary to show a certain modal for the 3 differentes cases.

CodePudding user response:

You can use every function on an array to check for all objects. Read about every.

const isAllNewInfo = data.every(item => item.isNew)
const isAllOldInfo = data.every(item => !item.isNew)


if (isAllNewInfo) {
  return this.explainNewInfo(true)
} else if(isAllOldInfo) {
  return this.explainNewInfo(false)
} else {
  return this.explainNewInfo()
}
  • Related