gpt4 book ai didi

javascript - 比较两个玩家分数数组,看看谁在列表中上升/下降

转载 作者:行者123 更新时间:2023-12-05 04:29:14 26 4
gpt4 key购买 nike

我有两个在不同时间段拍摄的数组。如何通过将新玩家标记为上升来检查哪些玩家在列表中上升/下降?

附言- 数组已经根据分数排序。

pastData:[

{
playerName:'John Doe',
score:50
},
{
playerName:'Jane Doe',
score:40
},
{
playerName:'John Appleseed',
score:30
},
{
playerName:'John Walker',
score:20
},
]

presentData:[

{
playerName:'Jane Doe',
score:80
},
{
playerName:'John Doe',
score:60
},
{
playerName:'John Appleseed',
score:40
},
{
playerName:'John Mayer',
score:30
},
]

我需要检查比较两个数组的索引变化并获得如下输出。

   presentData:[

{
playerName:'Jane Doe',
score:80,
position:'up'
},
{
playerName:'John Doe',
score:60,
position:'down'
},
{
playerName:'John Appleseed',
score:40,
position:'same'
},
{
playerName:'John Mayer',
score:30,
position:'up'
},
]

我正在尝试如下,但似乎无法为新播放器用例找到解决方案。

let status=[] //this array will include the changes 
which I can use later to update the presentData array
with a "position:'up/down/same'" key-value pairs.

for (let i = 0; i < 4; i++) {

for(let j=0; j<4; j++) {

if(Object.values(pastData)[i].id==Object.values(presentData)[j].id){
if(i==j){
status.push('same')

}
if(i<j){
status.push('down')

}
if(i>j){
status.push('up')
}
}

}



}

最佳答案

  1. 创建 Map从将 playerName 映射到他们的 indexpastData 数组中。

  2. 遍历 presentData 数组并使用 map 计算每个玩家的位置。

const pastData = [
{ playerName: "John Doe", score: 50 },
{ playerName: "Jane Doe", score: 40 },
{ playerName: "John Appleseed", score: 30 },
{ playerName: "John Walker", score: 20 },
];

const presentData = [
{ playerName: "Jane Doe", score: 80 },
{ playerName: "John Doe", score: 60 },
{ playerName: "John Appleseed", score: 40 },
{ playerName: "John Mayer", score: 30 },
];

const pastDataMap = new Map(pastData.map((d, i) => [d.playerName, i]));

const status = presentData.map((d, i) => {
const pastIndex = pastDataMap.get(d.playerName);
return {
...d,
position:
pastIndex === undefined || i < pastIndex
? "up"
: i > pastIndex
? "down"
: "same",
};
});

console.log(status);

其他相关文件:

关于javascript - 比较两个玩家分数数组,看看谁在列表中上升/下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72401269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com