Struggling to create a Javascript quiz for my coding bootcamp. I'm facing challenges with retrieving and saving previous high scores from local storage. Can someone explain why the newScore is being written TWICE to the highScores arrayItems array in local storage? I definitely don't want duplicates. Everything else is working perfectly except for this issue. Please provide your assistance. Thank you!
// Load any existing high scores from local storage as an array
let scoresArray = localStorage.getItem('highScores') ? JSON.parse(localStorage.getItem('highScores')) : [];
// Save the score and initials to local storage in an array
let newScore = [document.querySelector("#initialsInput").value, "" + countdownTimer + ""];
scoresArray.push(newScore);
localStorage.clear("highScores");
localStorage.setItem('highScores', JSON.stringify(scoresArray));
// Run the high scores function to display all high scores, sorted, and allow the user to play again
showHighScores();
Thank you for the prompt responses. I apologize for not providing all the necessary information, but I believed I gave you sufficient details to work with.
I wanted to inform you that I found a workaround. Although I'm still encountering duplicate entries in the array, before writing it to localStorage, I'm using a simple jQuery method to remove any duplicates from my array. Here's what I did:
var uniqueNames = [];
$.each(scoresArray, function (i, el) {
if ($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
})