Uncovering the Mystery: The Issue of Duplicate Items When Writing Arrays to localStorage in JavaScript

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);
        })



Answer №2

In my opinion, it would be beneficial to include a detailed description of the circumstances under which this implementation of adding an array to local storage might be triggered. There is a possibility that the array could be added twice if the code snippet provided is within a function or unclear in its execution. It appears that everything is functioning correctly based on the code provided, but it would be helpful to see more of your code to gain a better understanding of the situation. Additionally, it is worth noting that localStorage.setItem will automatically replace any existing key with a new value, so there is no need to use localStorage.clear.

Answer №3

An inefficient method incorporating jQuery to eliminate duplicates in the array:

let uniqueValues = [];
        $.each(dataArray, function (index, element) {
            if ($.inArray(element, uniqueValues) === -1) uniqueValues.push(element);
        })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disabling scrolling on body while scrolling a superimposed element

I am working on creating a dynamic image gallery for browsers that support Javascript. The gallery consists of thumbnails that lead to full-size photos displayed in a table layout, complete with navigation links and captions. This table is centered using f ...

The function req.send('null') does not exist in the Node.js MySQL library

I am struggling with inserting a form into a MySql database. The values are stored in the database from the form, but the table displayed on the page does not refresh. I can only see the entries when I restart the server and revisit the page. Furthermore, ...

Tips for accelerating the loading of data retrieved through ajax requests

At present, data is being fetched in array form from a PHP script. I have noticed that when retrieving 40 sets of data, it takes approximately 20 seconds for the data to load. This delay may be due to ajax having to wait until all the results are gathered. ...

I am having trouble establishing a connection to the JavaScript MQTT server

Error Encountered: WebSocket Error 12031 - The Server Connection Was Reset In order to subscribe to MQTT messages from the user interface, the code below is being utilized. A Mosquitto broker is currently running on my local machine, with the IP address s ...

What are the steps to execute a filter operation on a table by utilizing two select box values with jQuery?

I have a challenge with two dropdown menus. One contains names and the other subjects, along with a table displaying information in three columns: name, subject, and marks. I would like to implement a filter based on the selections in these two dropdowns. ...

Using canvas elements to position divs in three.js

I am currently in the process of developing a custom animation player using Three.js for rendering objects, which is functioning perfectly. However, I am encountering difficulty when trying to incorporate control options at the bottom of the player (such a ...

Avoid automatically scrolling to the top of the page when a link is clicked

Within my ASP.NET MVC 5 application, there exists a partial view containing the following code: <a href="#" onclick="resendCode()" class="btn btn-link btn-sm">Resend</a> Additionally, on the View, the resendCode() function is present: funct ...

How can I pass JSON data from a Java Swing application to a servlet? Should I use HTTP or sockets for this task?

Currently, I am using Eclipse Indigo and Tomcat 7.0 for my project. The project named "Controller" under the package "gui" is a Swing application aimed at creating a controller-tool for managing machine information settings. Within this application, there ...

Struggling to make comparisons with numerical data from MongoDB in an ExpressJS route

I am currently developing a website using Node.js, EJS template, MongoDB, and Express. I am working on implementing search functionality on my page using forms, but I am encountering a small issue. The problem is related to a logical issue in the search f ...

Breaking Long Strings into Multiple Lines Using React Material UI Typography

Currently, I am working with ReactJS and incorporating MaterialUI components library into my project. However, I have encountered a problem with the Typography component. When I input a long text, it overflows its container without breaking onto a new lin ...

Mastering MongoDB: The Art of Inserting Intricate Schemas

Currently, I am in the process of developing a "Test" system where each test consists of multiple questions with corresponding answers. To create the questions, I am receiving a JSON format from another server as follows: { requestType: 'Create ...

I'm a complete programming newbie and I want to start learning JavaScript, jQuery, and other programming languages. Where should I

Coming from a design background with zero programming knowledge, I have recently learned XHTML and CSS. Now, I am eager to expand my skills by mastering JavaScript, jQuery, and more. Where should I begin? This will be my first foray into programming. Whil ...

Looking to verify the existence of a div using jQuery once other jQuery functions have executed and created HTML?

Is there a way to verify if a specific element exists within newly added HTML after clicking a button? I attempted this code snippet: $(document).on('click', '#add-html-code', function() { if ($('#something').length ...

I am eager to develop a Loopback model tailored specifically for handling this JSON data

"US Virgin Islands": [ "Charlotte Amalie", "Christiansted", "Frederiksted", "Kingshill", "St John Island" ], I'm currently working with a JSON file that contains country names and corresponding cities. I want to store this data in my database using M ...

Deciphering intricate JSON values using the Lift-JSON library

In my Scala 2.12 project, I am attempting to utilize Lift-JSON for parsing a configuration file named myapp.json. The contents of the config file are as follows: { "health" : { "checkPeriodSeconds" : 10, "metrics" : { "stores" : { ...

Which JavaScript framework tackles the challenges of managing asynchronous flow, callbacks, and closures?

I have a strong aversion to JavaScript. I find it to be quite messy and disorganized as a language. However, I recognize that my lack of proficiency in coding with it may contribute to this perception. These past few days have been incredibly frustrating ...

Retrieve information from JSON Object by specifying the Value to extract_Object(s)(data)

What are the various methods for extracting object(s) based on a value from a JSON Object? Please refer to the JSON example below: { "ProductCollection": [ { "ProductId": "1239102", "Name": "Power Projector 4713", "Category": " ...

Tips for accessing array or JSON data with ReactJS

As a novice with the MERN stack, I have set up my express app to run on port 3001 with a dbconn route. When I access "localhost:3001/dbconn," it displays the docs array successfully. const mongoose = require('mongoose') const MongoClient = req ...

Steps for embedding a webpage within a div element

I am facing an issue while trying to load a web page within a div using an ajax call. Unfortunately, it's not working as expected and displaying the following error message: jquery.min.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread ...

Is there a way for me to update the placeholder text in my script from "CHANGE ME

Can anyone help me troubleshoot this code that's not working on my computer? I have a paragraph with the text CHANGE ME inside an element with the id "warning". I want to update this text when the login button is clicked, but it doesn't seem to ...