我有一个对象数组,想要找到分数最高且不超过某个分数的玩家(例如20分)。我该怎么办?
if(cell > x,1,0)
答案 0 :(得分:3)
您可以先过滤数据,按分数对其进行排序,然后选择第一个:
let filteredData = playerScores.filter(p=>p.score<=20).sort((a,b) => b.score-a.score);
let result = filteredData.length ? filteredData[0] : undefined;`
答案 1 :(得分:1)
一个简单的解决方案是创建一个获取极限分数并迭代 palyerScores 元素的函数,并在下面的示例中查找匹配元素
let playerScores = [
{
player: 'Dealer',
score: 19,
cards: 'A of ♥, 5 of ♦',
},
{
player: 'Player1',
score: 18,
cards: '10 of ♦, 8 of ♦',
},
{
player: 'Player2',
score: 23,
cards: '6 of ♦, 6 of ♥, J of ♠',
},
];
function getHighestScore(limitScore) {
let highestScore = 0;
let player = {};
for (let i = 0; i < playerScores.length; i++) {
if (
playerScores[i].score > highestScore &&
playerScores[i].score < limitScore
) {
highestScore = playerScores[i].score;
player = Object.assign({}, playerScores[i]);
}
}
return player;
}
let highsetScorePlayerNotExced20 = getHighestScore(20);
console.log(highsetScorePlayerNotExced20);
&#13;
答案 2 :(得分:1)
您可以使用链式检查条件并在必要时将对象添加到结果集中,或者将对象替换为具有更高分数的对象。
jump()
&#13;
答案 3 :(得分:0)
let playerScores = [
{ player: 'Dealer',
score: 19,
cards: 'A of ♥, 5 of ♦' },
{ player: 'Player1',
score: 18,
cards: '10 of ♦, 8 of ♦' },
{ player: 'Player2',
score: 23,
cards: '6 of ♦, 6 of ♥, J of ♠' }
];
const maxLimit = 20;
const maxScorePlayer = playerScores.reduce((prev, current) => {
if (current.score >= maxLimit) {
return prev;
}
return (prev.score > current.score) ? prev : current
}, { });
您可以查看缩减功能的工作原理here
答案 4 :(得分:0)
let playerScores = [
{ player: 'Dealer',
score: 19,
cards: 'A of ♥, 5 of ♦' },
{ player: 'Player1',
score: 18,
cards: '10 of ♦, 8 of ♦' },
{ player: 'Player2',
score: 20,
cards: '6 of ♦, 6 of ♥, J of ♠' }
];
var highestScore = Math.max.apply(Math,playerScores.map(function(o){
score = 0;
if(o.score != 20) {
score = o.score;
}
return score;
}));
console.log(highestScore);