简体   繁体   中英

Javascript sort object string with numbers

I have the following JSON object in javascript:

var stuff = [{
"id": "20",
"serial": "0/0/19:46,0/0/149:63"
}, {
"id": "8",
"serial": "0/0/151:215,0/0/151:233"
}, {
"id": "54",
"serial": "0/0/151:26,0/0/151:37"
}, {
"id": "22",
"serial": "0/0/155:29,0/0/155:36"
}, {
"id": "4",
"serial": "0/0/151:48,0/0/151:152"
}];

I would like to know how to sort the object by the "serial" field, leaving it like this (taking into account the value of the integers in the serial string):

var stuff = [{
"id": "20",
"serial": "0/0/19:46,0/0/149:63"
}, {
"id": "54",
"serial": "0/0/151:26,0/0/151:37"
}, {
"id": "4",
"serial": "0/0/151:48,0/0/151:152"
}, {
"id": "8",
"serial": "0/0/151:215,0/0/151:233"
}, {
"id": "22",
"serial": "0/0/155:29,0/0/155:36"
}];

Thanks in advance.

You have an array of objects, which you want to sort by one of their properties. You could very easily do it like this:

stuff.sort(function(a,b) {return a.serial == b.serial ? 0 : a.serial < b.serial ? -1 : 1;});

Alternatively, you could have a more general function:

function sort(input,prop) {
    input.sort(function(a,b) {return a[prop] == b[prop] ? 0 : a[prop] < b[prop] ? -1 : 1;});
}
// call with:
sort(stuff,'serial');

This will do it for you:

var normalizer = /[:\/]/g;

function serialCompare(a, b) {
    var alist = a.serial.replace(normalizer, ',').split(','),
       blist = b.serial.replace(normalizer, ',').split(','),
       i = 0, l = alist.length;
    while (alist[i] === blist[i] && i < l) {
        i += 1;
    };
    return (parseInt(alist[i], 10) - parseInt(blist[i], 10));
}

sortedstuff = stuff.sort(serialCompare);
// returns array sorted as you asked

See it in a fiddle .

If you are going to be sorting often, or the list is very long, you should consider creating a "normalized" version of the serial value that gets stored in the object. It could be the array as calculated inside the serialCompare function, or it could be the text number parts padded to the same lengths with leading zeroes.

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