简体   繁体   中英

How to sort a multidimensional array in JavaScript

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"
}]

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/

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'));
data.sort(function(a,b){return a.percentage - b.percentage});

参考

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM