Storing items in localStorage in the same order they were added

I am having an issue with sorting localStorage items by the order they were added. Despite my code working to add items to the localStorage array and display them as HTML, I am encountering a problem with the order of the items.

When I add a 3rd item to the array, it unexpectedly becomes the 2nd item in the displayed list. It seems that the items are appearing in a random order, which is confusing me.

Below is the code snippet I have been working on:

<body>

        <h2>Local Storage - JavaScript</h2>

        <form method="post" action="index.html" id="form">
            <fieldset>
                <legend>Insert Data</legend>
                <input id="enterKey" type="text" placeholder="Enter Key...">
                <input id="enterValue" type="text" placeholder="Enter Value...">
                <input type="submit" value="Set Reminder">
            </fieldset>
        </form>

        <ul id="output">
        </ul>

    </body>

    <script>
        form.addEventListener('submit', function(e) {

            const key = enterKey.value;
            const value = enterValue.value;

            if (key && value) {
                localStorage.setItem(key, value);
            }

        })

        for (let i = 0; i < localStorage.length; i++) {

            const key = localStorage.key(i);
            const value = localStorage.getItem(key);

            var li = document.createElement("li");
            li.textContent = `${key}: ${value}</li>`;
            output.appendChild(li);

        }
   </script>

Answer №1

The arrangement of items within localStorage is not guaranteed due to the key-value pair storage method it uses, which does not maintain a specific order. Some programming languages intentionally randomize the ordering to prevent reliance on any particular sequence. To impose ordering, an ordering key must be incorporated into the data itself, allowing items to be sorted based on that key.

For example:

form.addEventListener('submit', function (e) {
  const key = enterKey.value;
  const value = enterValue.value;
  if (key && value) {
    const count = localStorage.length;
    const val = {
      value,
      order: count,
    }
    localStorage.setItem(key, val);
  }

})

const items = [];
for (let i = 0; i < localStorage.length; i++) {
  const key = localStorage.key(i);
  const value = localStorage.getItem(key);
  items.push({key, value});
}
items.sort((a, b) => a.value.order - b.value.order).forEach(item => {
  var li = document.createElement("li");
  li.textContent = `${item.key}: ${item.value.value}</li>`;
  output.appendChild(li);
});

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

How to show dates in AngularJS using local formatting

One situation I'm dealing with involves setting a date for an event. The challenge is that the date picker needs to display the date in a localized format based on the country or region. I've been exploring various solutions in AngularJS, but so ...

Displaying outcomes solely based on JSON upon choosing a filter

Goal I aim to only show results once their respective state is chosen. Currently, all results are displayed automatically upon page load. I prefer if nothing is shown initially. Only when a state is selected should the corresponding results appear. Bac ...

Is it possible to call a REST API in Javascript by passing the username and password as

I have been attempting to use Javascript to call the AwaazDe REST API with a specific username and password, but I'm encountering issues. Below is my code: function authenticateUser(user, password) { var token = user + ":" + password; ...

What is the best way to keep tab content fixed when switching?

I've successfully implemented tab switching, but I need to make the content fixed. How can I achieve this so that no matter the length of the content, it remains fixed in its position when switching tabs? The current issue is that when the content is ...

Can we expand the capabilities of a ThreeJS object in any way?

In my ThreeJS project, I am implementing an interactive feature where users can click on cubes that behave differently when clicked, such as having different color animations. To achieve this, I plan to create extension classes for the THREE.Mesh object a ...

How to set the element in the render method in Backbone?

Currently, I am in the process of developing a web page utilizing BackboneJS. The structure of the HTML page consists of two divs acting as columns where each item is supposed to be displayed in either the first or second column. However, I am facing an is ...

Puzzling array challenge. Lack of clarity in explanation

I am currently working on a series of JavaScript tests available at js-assessment One of the tasks states: it("you should be able to find all occurrences of an item in an array", function() { var result = answers.findAllOccurrences('abcdefab ...

Steps to create a toggle click event

I've been attempting to create a toggle click event using the code below: HTML <a class="load" data-gallery="123456" style="cursor: pointer;"><h2><p>example</p></h2></a> <div id="123456"> </div> j ...

Issue with VueJS 2 and TypeScript: computed value unable to recognize property specified in data object

When creating the following component: <template lang="html"> <div> <p>{{ bar }}</p> </div> </template> <script lang="ts"> import Vue from 'vue'; export const FooBar = Vue.ex ...

Why isn't my watch function functioning properly within Vue?

In my JS file, I have two components. The file starts with this line: const EventBus = new Vue(); I am trying to pass two strings, 'username' and 'password', from the first component to the second component, but it's not working. ...

Discord bot that combines the power of discord.js and node.js to enhance your music

I am currently working on a Discord bot designed to play music in voice chat rooms. However, I am facing some issues with properties. Whenever I try to launch the bot using "node main", I encounter the following error message: "TypeError: Cannot read prope ...

The value of a variable remains constant in an Angular controller

I am facing an issue with my HTML page that includes: <div ng-controller="MyCtrl"> <div ng-view>Some content</div> myVar: {{myVar}} </div> Along with an Angular controller: myModule.controller('MyCtrl', function($s ...

Image Placement Based on Coordinates in a Graphic Display

Placing dots on a map one by one using CSS positions stored in arrays. var postop =[{'top':'23'},{'top':'84'},{'top':'54'},{'top':'76'},{'top':'103'}]; var ...

How do I rearrange the order of a collection in Firestore using a reference that I already have?

Is there a method to maintain a reference of the same collection while altering the ordering using firestore? TLDR: I am looking to achieve similar functionality as demonstrated in: , but since my data is sourced from firestore, I am struggling to find th ...

Retrieve the $$state value from the Service Function

I am new to Angular and struggling to understand a function in my service. I have this code snippet: checkRoomNameStatus: function() { var promises = []; var emptyRooms = []; DatabaseService.openDB().transaction(function(tx) { tx.exec ...

How can I wait for an onclick action to pause, loop, or continue inside of a loop?

The form's onsubmit function triggers a pop-up message asking the user if they want to proceed before submitting the form. This requires the onsubmit function to wait for the user's final input in order to fully execute the form. Here is the cod ...

When attempting to update my avatar using client.user.setAvatar(), the desired changes fail to take effect

Currently, I am attempting to update the bot avatar with a specific user's avatar, but I seem to be encountering some difficulties. I have attempted the following code: client.users.fetch('userid').then((user) => { client.user.setAva ...

What steps need to be taken to utilize the fast-json package within a web browser environment?

In my quest to enhance the performance of my apps, I stumbled upon two intriguing packages. Currently, I am working on a forum-style app that constantly receives and processes information from APIs. Despite optimizing my frontend JavaScript to the best of ...

Bootstrap 4 Card Body Spinner Overlay with Flex Alignment

Seeking to center a spinner both vertically and horizontally within a bootstrap 4 card body. Despite trying my-auto, justify-content-center & align-items-center, it seems like I'm missing something. I've double-checked the display types and ...

Using three.js for creating particle systems with custom particle geometries

In my three.js project, I am working with a standard system of particles. However, I am curious if it is feasible to use different geometries for the particles, like boxes or planes. I am attempting to create falling bullet particles, but I am facing an is ...