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 ?
flyingfox
13.5k4 gold badges30 silver badges43 bronze badges
-
The reason is that you store it as object and you have duplicate keyflyingfox– flyingfox2022年10月20日 01:59:10 +00:00Commented Oct 20, 2022 at 1:59
1 Answer 1
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"]));
answered Oct 20, 2022 at 2:01
flyingfox
13.5k4 gold badges30 silver badges43 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js