I have a simple function that checks if the username already exists in the array of objects, in case it does, it should save new time in an array in format { username: username, time: [firsttime, secondtime, etc] }. The code itself is rough, but the problem is that if the username doesn't exist (and the array is not empty, so there are some other usernames saved already), the function saves the time two times, if I try the same username, I get one more object with double time.
let array = []
const userName = prompt("username")
const userTime = prompt("points")
if (array.length > 0) {
for (let i = 0; i < array.length; i++) {
if (array[i].username === userName) {
array[i].time.push(userTime)
} else {
const thisTime = {
username: userName,
time: [userTime]
}
array.push(thisTime)
}
}
} else {
const firstTime = {
username: userName,
time: [userTime]
}
array.push(firstTime)
console.log(array)
}
So on the first round i get [{username: "maria", time: Array(1)}]
On the second round with another username [{username: "maria", time: Array(1)}, {username: "ariana", time: Array(2) e.g. [14,14] (should be only 1 value)}]
The code was edited according to the rules, so actual username and time are added in course of the game.