Home > other >  How to read array elements into given object in JS
How to read array elements into given object in JS

Time:10-20

i am trying to read the array elements into the object as follows

function points(games){
    let scoreBoard = {};
    for(let i = 0 ; i < games.length ; i  ){
        let otherTeam = 0;
        let ourTeam = games[i][0];

        for(let j = 0 ; j < games[i].length; j  ){
            otherTeam = games[i][j];
        }
        scoreBoard[ourTeam] = otherTeam;
    }
  return scoreBoard;
}

console.log(points(["1:0","2:0","3:0","4:0","2:1","3:1","4:1","3:2","4:2","4:3"]));

I want it to read in in the [x:y] format, i am missing something. Can you please help me ?

CodePudding user response:

The reason is that you defined result as let scoreBoard = {},it's an object and it stores values based on key,but you have multiple duplicate key,such as 4:1,4:2,4:3,the key of them are 4,so the last record will override the previous one.

In order to store all the scores,there are multiple options,such as make the key unique or using array to store it

function points(games){
    let scoreBoard = [];
    for(let i = 0 ; i < games.length ; i  ){
        let otherTeam = 0;
        let ourTeam = games[i][0];

        for(let j = 0 ; j < games[i].length; j  ){
            otherTeam = games[i][j];
        }
        scoreBoard.push({[ourTeam]:otherTeam})
    }
  return scoreBoard;
}

console.log(points(["1:0","2:0","3:0","4:0","2:1","3:1","4:1","3:2","4:2","4:3"]));

  • Related