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?

2
  • 1
    Hi, take a look at <linqjs.codeplex.com> i think that contains what you need. It is what i found at first search on google:) Commented Aug 8, 2015 at 16:35
  • cool - thanks. looks good Commented Aug 8, 2015 at 16:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

It would be better to use var sortedCached4 = cached4.sort(function (a, b) { return a.TS - b.TS; });
> will sort as a string, use ´-´ to sort as numbers. This maybe irrelevant in the concrete case but for others it can be useful
@CraigStroman and simon, you are both correct. Changed the comparison, thanks.
Thanks for that info. I have supplied smaller number. Cheers :)
@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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.