按公共字段排序数组(javasciript)

时间:2017-03-22 15:14:01

标签: javascript arrays sorting

我有一个对象数组,我想按常见类型对其进行排序。 有些对象的类型为'x',有些为'y',有些为'z'。

现在,我可以对它进行排序并将所有'x'放在前面。但是,我想对'y'和'z'做同样的事情。
最后,所有'x'都在前面,然后是'y',然后是'z'。

[['a'], ['a', 'b']]

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以使用排序顺序type的对象。

var list = [{ type: 'a', name: 'z' }, { type: 'b', name: 'a' }, { type: 'c', name: 'b' }, { type: 'x', name: 'c' }, { type: 'x', name: 'd' }, { type: 'y', name: 'e' }, { type: 'y', name: 'f' }, { type: 'z', name: 'g' }, { type: 'z', name: 'h' }, ]

list.sort(function (a, b) {
    var order = { x: -1, y: -1, z: -1, default: 0 };
    return (order[a.type] || order.default) - (order[b.type] || order.default) || a.name.localeCompare(b.name);
});

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

适用于

{
    f: -2,         // top
    x: -1,         // \
    y: -1,         //   a group after top
    z: -1,         // /
    default: 0     // a default value for not mentioned types for sorting in the middle
    a: 1           // after the common parts
    d: 2           // bottom
}

答案 1 :(得分:0)

一个简单的解决方案是为类型定义数字顺序,并使用经典方法通过数字属性对对象数组进行排序:

var order = {'x': 0, 'y': 1, 'z': 2}
var data = [
  {type: 'z'},
  {type: 'y'},
  {type: 'x'},
  {type: 'x'},
  {type: 'y'},
  {type: 'z'}
]

var sortedData = data.sort(function(a, b) {
  return order[a.type] - order[b.type]
})

console.log(sortedData)

请注意,您可能希望包含一些错误处理,例如对于未在order地图中维护的类型。

相关问题