3

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.

2
  • 7
    players.every(player => player.isReady) Commented Sep 8, 2020 at 16:18
  • When are the same? or when all are TRUE? Commented Sep 8, 2020 at 16:23

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.