我有两个数组,它们是在不同的时间段内获取的.如何判断列表中哪些球员上升/下降,并将新球员标记为上升?

P、 数组已经根据分数进行了排序.

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'
    },
  ]

我try 如下,但似乎无法找到新玩家用例的解决方案.

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. 创建pastData数组中的Map,将playerName映射到index.

  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);

Other relevant documentations:

Javascript相关问答推荐

复合密钥查找在mongoDB中未按预期工作

我无法使用tailwind-css和reactJS修改图像的位置

我不明白这个react 组件有什么问题

React对话框模式在用户单击预期按钮之前出现

Flisk和JS错误:未捕获的Syntax错误:意外的令牌'<'

将数据从strapi提取到next.js,但响应延迟API URL

使用print This时, map 容器已在LeafletJS中初始化

Cypress -使用commands.js将数据测试id串在一起失败,但在将它们串在一起时不使用命令有效

InDesign—创建一个独立的窗口,在文档中进行更正时保持打开状态

如何找出摆线表面上y与x相交的地方?

PrivateRoute不是路由组件错误

为什么Mutations 观察器用微任务队列而不是macrotask队列处理?

可更改语言的搜索栏

我可以使用空手道用户界面来获取网页的当前滚动位置吗?

如何将zoom 变换应用到我的d3力有向图?

如何在 Select 文本时停止Click事件?

将Auth0用户对象存储在nextjs类型脚本的Reaction上下文中

在GraphQL解析器中修改上下文值

MongoDB通过数字或字符串过滤列表

P5.js中矩形内的圆弧