3

I generally post the code I have so far, but I have nothing on this one... :(

How would I go about re-ordering the following array so that I can base it on the value in the 'percentage' key, either low-to-high or high-to-low?

var data = [{
    "id": "q1",
    "question": "blah blah blah",
    "percentage": "32"
}, {
    "id": "q2",
    "question": "blah blah blah",
    "percentage": "23"
}, {
    "id": "q3",
    "question": "blah blah blah",
    "percentage": "11"
}, {
    "id": "q4",
    "question": "blah blah blah",
    "percentage": "3"
}, {
    "id": "q5",
    "question": "blah blah blah",
    "percentage": "6"
}]
1
  • 2
    That's not a multidimensional array. It's an array of objects. Commented May 31, 2012 at 5:50

3 Answers 3

5

A bit of correction, it's not a multidimensional array, it's an array of objects, you most likely mixed up the naming from PHP, for your question, use the optional function argument of sort to define your own sorting order.

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

// sorted data, no need to do data = data.sort(...);

http://jsfiddle.net/cEfRd/

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

Comments

4

Sorter generator, generalizing https://stackoverflow.com/users/135448/siganteng answer so that it works on any property

function  createSorter(propName) {
    return function (a,b) {
        // The following won't work for strings
        // return a[propName] - b[propName];
        var aVal = a[propName], bVal = b[propName] ;
        return aVal > bVal ? 1 : (aVal < bVal ?  - 1 : 0);

    };
}
data.sort(createSorter('percentage'));

Comments

2
data.sort(function(a,b){return a.percentage - b.percentage});

The Ref.

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.