I’m no Javascript expert and I’m having problems trying to glue together the various nuggets I find here and elsewhere regarding multi-dimensional arrays and sorting and wondered if someone could help me with a complete example?
I have managed to get to the point that I can populate a localStorage with data read in via Ajax.
The format of the rows is …
(msgXXX) (Key1:Value1|Key2:Value2|Key3:Value3|…etc)
where
(msgXXX) is the localStorage key; and
(Key1:Value1|Key2:Value2|Key3:Value3|…etc) is the single concatenated localStorage data string
What I want to be able to do is convert all this to a multi-dimensional array to which I can apply various sorts. For example, one of the Keys is called "Timestamp" and the value is an integer representing seconds since the Unix epoch. I would like to sort all rows based on this Timestamp value (in descending order – ie latest first). Right now the dataset is just over 600 rows.
I’m comfortable I can do the extraction and slicing and dicing to get the data out of the localStorage, but I’m not even sure what I’m aiming for with regards to populating an array and then setting up the sort.
Can someone point me in the right direction?
You can go with something like this:
This code creates an object per key/value line, in the format you gave. The object will have the keys as attributes. All of those objects are being pushed into an array, which is then being sorted by passing a compare function to the native sort method of array.
You can of course make as many compare functions as you want, each comparing by a different attribute/criteria.
You can read more about the sort method here: http://www.w3schools.com/jsref/jsref_sort.asp
EDIT
The sort method both changes the array itself and returns the array, so doing something like:
Will both change the actual array and return it, and so the console.log will print it.
If you don’t want to change the original array and have a copy of it that will get sorted you can:
As for the keys in the array, what I wrote was intended to work only with this part of the line: Key1:Value1|Key2:Value2|Key3:Value3|…etc
So, to add support for the entire format, here’s the modification:
If you apply this to the example you gave you’ll get this:
Hope this clears things for you.