最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if all property values are the same in an Array of Objects - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question asked Sep 8, 2020 at 16:16 CarlssonKCarlssonK 1564 silver badges11 bronze badges 2
  • 7 players.every(player => player.isReady) – Andrew Li Commented Sep 8, 2020 at 16:18
  • When are the same? or when all are TRUE? – Ele Commented Sep 8, 2020 at 16:23
Add a ment  | 

1 Answer 1

Reset to default 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
发布评论

评论列表(0)

  1. 暂无评论