JohnRobertPett
JohnRobertPett

Reputation: 1183

Order an object from array order

I am trying to order a JSON object, by using an integer value which is nested in it. the approach I have taken is to order the incoming data as readably as possible. Which I create a new JSON object with:

var newDataFormat = {"route": route, "destination": destination, "countdown": countdown};

busJSON.push(newDataFormat);

Then I create an array to act as the ordering mechanism. Which takes the 'countdown' integer, and then sorts by that number:

for (var i = totalStops - 1; i >= 0; i--) {

    countdownArray.push(parseInt(busJSON[i].countdown));

}

countdownArray.sort(function(a,b){return a - b});

Once I have these, I have one last loop, to push the information to the browser:

for (var i = dataMin; i < dataMax; i++) {

    if (countdownArray[i] === i) {

        items.push("<tr><td>" + busJSON[i].route + "</td><td>" + busJSON[i].destination + "</td><td>" + busJSON[i].countdown + "</td></tr>");

    }

}

The problem seems that it doesn't quite push all of the items to the browser, which I have made a demo of here:

http://tfl.applied-espi.com/bus-popup/

Is there a more correct/efficient way I should be doing this?

Upvotes: 1

Views: 93

Answers (1)

Theofilos Mouratidis
Theofilos Mouratidis

Reputation: 1156

An array is also a valid json format, so you can have

var busJSON = [];

then you push some objects to it and want to order them by a member of the objects

busJSON.push({"route": route, "destination": destination, "countdown": countdown});

so you have now an array of objects, as we know an array can be sorted so we sort it by its countdown value

busJSON.sort(function(a,b){return a.countdown - b.countdown});

now we have the objects sorted in ascending order, so we do some action for each element in the array

busJSON.forEach(function(value) {
    items.push("<tr><td>" + value.route + 
              "</td><td>" + value.destination +
              "</td><td>" + value.countdown + "</td></tr>");
});

voila!

Upvotes: 1

Related Questions