按字符串值排序对象数组

时间:2018-01-17 15:02:21

标签: javascript sorting

我有这个对象

var obj = [
    {id: 31, name: "Tiebreak 1", type: 2},
    {id: 32, name: "Tiebreak 2", type: 2},
    {id: 25, name: "Set 1", type: 0},
    {id: 33, name: "Tiebreak 3", type: 2},
    {id: 26, name: "Set 2", type: 0},
    {id: 34, name: "Tiebreak 4", type: 2},
    {id: 35, name: "Tiebreak 5", type: 2},
    {id: 27, name: "Set 3", type: 0},
    {id: 28, name: "Set 4", type: 0},
    {id: 29, name: "Set 5", type: 0}
]

我怎么能这样排序?

var obj = [
    {id: 25, name: "Set 1", type: 0},
    {id: 31, name: "Tiebreak 1", type: 2},
    {id: 26, name: "Set 2", type: 0},
    {id: 32, name: "Tiebreak 2", type: 2},
    ...
]

2 个答案:

答案 0 :(得分:1)

你可以这样做:

var obj= [{id:31,name:"Tiebreak 1",type:2},{id:32,name:"Tiebreak 2",type:2},{id:25,name:"Set 1",type:0},{id:33,name:"Tiebreak 3",type:2},{id:26,name:"Set 2",type:0},{id:34,name:"Tiebreak 4",type:2},{id:35,name:"Tiebreak 5",type:2},{id:27,name:"Set 3",type:0},{id:28,name:"Set 4",type:0},{id:29,name:"Set 5",type:0}]

console.log(obj.sort(function(a, b) {
  return a.name.split(' ')[1] - b.name.split(' ')[1] || a.name.localeCompare(b.name);
}));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

您可以将相同的号码组合在一起,然后按'Set''Tiebreak'排序。

var array = [{ id: 31, name: "Tiebreak 1", type: 2 }, { id: 32, name: "Tiebreak 2", type: 2 }, { id: 25, name: "Set 1", type: 0 }, { id: 33, name: "Tiebreak 3", type: 2 }, { id: 26, name: "Set 2", type: 0 }, { id: 34, name: "Tiebreak 4", type: 2 }, { id: 35, name: "Tiebreak 5", type: 2 }, { id: 27, name: "Set 3", type: 0 }, { id: 28, name: "Set 4", type: 0 }, { id: 29, name: "Set 5", type: 0 }];

array.sort(function (a, b) {
    function getParts(o) {
        return o.name.split(' ');
    }
    var order = { Set: 1, Tiebreak: 2 },
        aa = getParts(a),
        bb = getParts(b);

    return aa[1] - bb[1] || order[aa[0]] - order[bb[0]];
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }