简体   繁体   中英

How to sort a JSON object in javascript or jquery with the following format

"attributes": [
    "BytesServed",
    "Duration",
    "UniqueIPAddresses",
    "StopEvents",
],
"rows": [
    [
        "12118931578714",
        "160557966.305",
        "372",
        "193381",
    ],
    [

        "248313315029",
        "4628315.959",
        "350",
        "27352",

    ],
]

I have 2 arrays, where the first array has keys and the second array is a multi-dimensional array with values.

Is there any pre-defined function in Javascript or jQuery which will give me the values in descending order by passing a key?

I have a solution, but I feel that it is a more costly approach. If anybody has better solution please let me know.

My current solution is -- get the index from the first array and loop through the second array and create a temporary array and then sort that temp array and use it.

You don't need to create a temporary array. Once you get the index of the attribute you're looking for (and for this example I shall assume it's in a variable called index and that the whole JSON object is in jsondata ), just a simple sort will do:

jsondata.rows.sort(function(a,b) {
    return a[index]-b[index];
});

And there you have your sorted array.

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