0

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.

5
  • Please update the snippet I made you with relevant code to make a minimal reproducible example Commented Jan 27, 2020 at 14:18
  • Should I rewrite the code with different variables? Commented Jan 27, 2020 at 14:39
  • No, you need to update to a working example with a set of example points Commented Jan 27, 2020 at 14:40
  • It would be too much code to write the whole working version, so I have updated to more or less working one. But I already got an answer anyway, thank you. Commented Jan 27, 2020 at 14:53
  • That is fine. Thanks Commented Jan 27, 2020 at 14:54

1 Answer 1

2

You could do that with a more efficient and less error prone way:

// look for the index in the array
const pointIndex = this.points.findIndex(point => point.username === this.username);

if(pointIndex > -1){ // if found, push the time
  this.points[pointIndex].time.push(this.globalTime);
}
else { // push a new point otherwise
  const thisTime = {
    username: this.username,
    time: [this.globalTime]
  }
  this.points.push(thisTime)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.