1

I have a list of JSON objects in my javascript code:

var cached4= [];

cached4.push({ Frame: 'frame', TS: 20150809101523723 });
cached4.push({ Frame: 'frame', TS: 20150809101513165 });
cached4.push({ Frame: 'frame', TS: 20150809101514988 });

I now want to reorder this array in TS order so that my result would be like this:

20150809101513165 
20150809101514988 
20150809101523723 

Now obviously I can enumerate through the array like so:

cached4.forEach(function (entry) {
    cached4.shift();

});

But is there a 'linqy' type of way of ding this?

Andrew Simpson
  • 6,883
  • 11
  • 79
  • 179

1 Answers1

3

You can use Array.prototype.sort:

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

var sortedCached4 = cached4.sort(function (a, b) { 
  return a.TS - b.TS;
});

Which sorts the values by ascending TS:

[
  {"Frame":"frame","TS":20150809101513165},
  {"Frame":"frame","TS":20150809101514988},
  {"Frame":"frame","TS":20150809101523723}
]

Edit: Note that your TS is larger than the safest integer value of 9007199254740991 which means that they lose precision, see What is JavaScript's highest integer value that a Number can go to without losing precision? for more information.

To test it out, enter 20150809101513165 to a console and see the result.

edit 2: As pointed out in the comments, comparing with - is better.

Community
  • 1
  • 1
Pete TNT
  • 8,293
  • 4
  • 36
  • 45
  • 1
    It would be better to use var sortedCached4 = cached4.sort(function (a, b) { return a.TS - b.TS; }); – Craig Stroman Aug 08 '15 at 16:41
  • 1
    `>` will sort as a string, use ´-´ to sort as numbers. This maybe irrelevant in the concrete case but for others it can be useful – smnbbrv Aug 08 '15 at 16:41
  • 1
    @CraigStroman and simon, you are both correct. Changed the comparison, thanks. – Pete TNT Aug 08 '15 at 16:43
  • Thanks for that info. I have supplied smaller number. Cheers :) – Andrew Simpson Aug 08 '15 at 16:51
  • @AndrewSimpson if TS means time stamp, you should parse the numbers as dates before sorting (you'll have to roll your own parser, since `new Date(TS)` probably won't work). – royhowie Aug 08 '15 at 18:23