1

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?

2
  • Could you post an example of the full json string? Commented Nov 26, 2013 at 12:31
  • 1
    Technically object properties don't have an order (at least in ECMAScript). Anyways, you need to maintain the key association, which it looks like you're losing when pushing countdown... stackoverflow.com/questions/3824392/… Commented Nov 26, 2013 at 12:32

1 Answer 1

1

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!

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

Comments

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.