简体   繁体   中英

Check if all property values are the same in an Array of Objects

I have an array of objects all with the same property name with isReady. I want to fire up a function when all objects isReady property is true.

let players = [
 0: {isReady: true}, 
 1: {isReady: false}, 
 2: {isReady: true}
]

Should return false

let players = [
 0: {isReady: true}, 
 1: {isReady: true}, 
 2: {isReady: true}
]

Should return true

for(let i = 0; i < players.length; i++) {
  if(players[i].isReady === true) {
    startGame()
  }
}

I've tried to loop all objects but the if statement returns true if even if 1 object has a true value.

You can achieve this in two ways

1- By using array inbuilt method every which will return boolean after checking full array. Example-

let players = [
{isReady: true}, 
 {isReady: true}, 
  {isReady: true}]
const isPlayersReady = players.every(data=> data.isReady)
if(isPlayersReady ){
startGame()
}

2- By using the Set data structure

let result = players.map(a => a.isReady);
console.log(new Set(result).size === 1); // True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM