0

Edit: Someone flagged this as a duplicate, I already read the question that marked as duplicate on this one. But I think this question is different since mine is related to local storage, and the other one isn't.

tl;dr: Is it possible to sort the data in Local Storage based on data field?

Right now I am trying to use local storage in an application I'm building in Cordova.

Since Cordova based on JS, everything seems normal with my code. Except I want to sort the data in local storage for some reason.

And I am confused, can we sort the order of the data based on the field?

i.e I have this json stored in local storage: [{a:1,b:1},{a:3,b:3},{a:2,b:4}]. And I want to sort it based on a, so it will be like this [{a:1,b:1},{a:2,b:4},{a:3,b:3}].

If it is possible, how to do it? And where do I need to do it? Before save the data to local storage or when me call out the data from local storage?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
vl14b
  • 85
  • 2
  • 14
  • Quick answer ~ `arr.sort((a, b) => a.a - b.a)`. Your second question about *"when"* is too broad to be answered – Phil Aug 24 '17 at 03:27
  • 1
    Presumably before putting it in storage it is an array, so just use the `.sort()` method on the array before you use `JSON.stringify()`. (Or use `.sort()` after you call `JSON.parse()` when you get it out of storage.) – nnnnnn Aug 24 '17 at 03:27
  • @Phil i see, so its how it is work. And yeah, you are right about it became too broad to be answered. But thanks anyway to have your time answer my question – vl14b Aug 24 '17 at 03:42
  • @nnnnnn hmm, your one is correct, i can just do something like that. Thanks for the asnwer ! – vl14b Aug 24 '17 at 03:44

0 Answers0