I am working with an API which returns an array of objects. Each object has an ID, and it also specifies which object comes before itself and after itself with a beforeId
and afterId
property. If it's the first object in the list, then the beforeId
is null (since nothing is before it in the list) and if it's the last object in the list, then the afterId
is null.
Example response from API:
var myUnorderedObjects = [
{ id: 896, beforeId: 392, afterId: 955 },
{ id: 955, beforeId: 896, afterId: null }
{ id: 451, beforeId: null, afterId: 392 },
{ id: 392, beforeId: 451, afterId: 896 },
]
Example of an ordered array:
var myOrderedObjects = [
{ id: 451, beforeId: null, afterId: 392 },
{ id: 392, beforeId: 451, afterId: 896 },
{ id: 896, beforeId: 392, afterId: 955 },
{ id: 955, beforeId: 896, afterId: null }
]
What is the best way to order these objects? Currently, my application implements its own ordering logic which is separate from the API's. I'd like to make them consistent. My general approach so far is to find the first object by identifying the one with null
set on the beforeId
, and then look up and find each one specified in the afterId
, but that just seems a bit... rubbish.
My application uses Underscore.js, so I'm happy for any answers to make use of this library.
Edit
I did a quick performance test between the two answers. Nina Scholz's answer was the fastest, and also an approach I hadn't even considered. http://jsperf.com/order-objects-with-beforeid-and-afterid