Compare two arrays of player scores to see who has gone up/down in the list

Issue

I have two arrays which are taken in different time periods. How to check what player has gone up/down in the list with the inclusion of marking a new player also as going up?

P.S. – Arrays are already sorted according to the score.

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

I need to check the index changes comparing the two arrays and get an output like following.

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

I’m trying as below but can’t seem to find a solution for the new player usecase.

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')
     }
   }

  }

  

}

Solution

  1. Create a Map out of the pastData array which maps the playerName to their index.

  2. Iterate over the presentData array and using the map calculate the position for every player.

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:

Answered By – SSM

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.