首页 > 解决方案 > Comparing values in two arrays

问题描述

I need some advice here. I have two arrays, with data that can be the same. I will compare these two row by row.

lastLoop [
  { position: '0', id: '5f862368df7d2700174c9df7' },
  { position: '1', id: '6111697148108400154a7cf9' },
  { position: '2', id: '610c1a8b132a880015c16a9d' },
  { position: '3', id: '5f8625e7df7d2700174c9df8' },
  { position: '4', id: '5fae7f6526ec3b0017710e60' },
  { position: '5', id: '61153dadd7db540015836e8e' },
  { position: '6', id: '5f849db0b0793b00177e2317' },
  { position: '7', id: '5fa85aba9c4a1900177e5cf9' },
  { position: '8', id: '6144d97107efcf001584706e' },
  { position: '9', id: '5e4463a395c832405e7effc5' }
]
newLoop [
  { position: '0', id: '5f862368df7d2700174c9df7' },
  { position: '1', id: '610c1a8b132a880015c16a9d' },
  { position: '2', id: '5fd7b30abb015f0017eda459' },
  { position: '3', id: '5fce234f9a61c100175f4b6d' },
  { position: '4', id: '5fca23930aa5e9001797a885' },
  { position: '5', id: '5f806a8b045fdf0017734fe8' },
  { position: '6', id: '5fc10c379378110017477dca' },
  { position: '7', id: '61153dadd7db540015836e8e' },
  { position: '8', id: '5f9b2c579050d2001785a253' },
  { position: '9', id: '5e4463a395c832405e7effc5' }
]

I want to make a leaderboard, if your position has changed up in the ladder, you get a green text, if it is the same, you get black text, if you have moved down the ladder you get a red text.

Any ideas?

标签: javascriptnode.js

解决方案


I would make a new object with an old_position key, based on this value you can decide what color you want to use.

const oldLeaderboard = [
  { position: '0', id: '5f862368df7d2700174c9df7' },
  { position: '1', id: '6111697148108400154a7cf9' },
  { position: '2', id: '610c1a8b132a880015c16a9d' },
  { position: '3', id: '5f8625e7df7d2700174c9df8' },
  { position: '5', id: '61153dadd7db540015836e8e' },
  { position: '4', id: '5fae7f6526ec3b0017710e60' },
  { position: '6', id: '5f849db0b0793b00177e2317' },
  { position: '7', id: '5fa85aba9c4a1900177e5cf9' },
  { position: '8', id: '6144d97107efcf001584706e' },
  { position: '9', id: '5e4463a395c832405e7effc5' }
]

const newLeaderboard = [
  { position: '0', id: '5f862368df7d2700174c9df7' },
  { position: '1', id: '610c1a8b132a880015c16a9d' },
  { position: '2', id: '5fd7b30abb015f0017eda459' },
  { position: '3', id: '5fce234f9a61c100175f4b6d' },
  { position: '4', id: '5fca23930aa5e9001797a885' },
  { position: '5', id: '5f806a8b045fdf0017734fe8' },
  { position: '6', id: '5fc10c379378110017477dca' },
  { position: '7', id: '61153dadd7db540015836e8e' },
  { position: '8', id: '5f9b2c579050d2001785a253' },
  { position: '9', id: '5e4463a395c832405e7effc5' }
]

const leaderBoard = newLeaderboard.map( item => ({
  posisiton: item.position,
  old_position: oldLeaderboard.filter(old => old.id === item.id)[0]?.position || null,
  id: item.id
}))

console.log(leaderBoard)


推荐阅读