How to sort localStorage by key

For some reason localStorage don’t sort by the order you add data to it.

I have stored JS date milliseconds as keys in localStorage.
How can i output the key and the value from localStorage sorted by key asc?

Do i need to create another VAR from localStorage and then sort the VAR?

Answer

How about saving the times as a single object using JSON.stringify(yourObject)

Something like

const jsTimes = localStorage.getItem("times");
const times = jsTimes ? JSON.parse(jsTimes) : {};
...
times[new Date().getTime()] = "Now is the time";
localStorage.setItem("times",JSON.stringify(times));

Alternatively if you must

const times = Object.keys(localStorage)
  .filter(key => key.length === 13 && !isNaN(new Date(key))
  .map(key => key)
  .sort() // alphabetic sort is ok on a timestamp
  .map(key => ({[key]: localStorage[key] }));

Leave a Reply

Your email address will not be published. Required fields are marked *