如何在jQuery中按特定顺序对对象数组进行排序

时间:2018-07-25 06:28:14

标签: javascript jquery arrays

嗨,我想按特定顺序对对象数组进行排序。我在排序之前给出了数组:

var arrayBeforeSort = [
    {simulationID: '45679', colorName:'Green'},
    {simulationID: '45672', colorName:'red'},
    {simulationID: '45676', colorName:'yellow'},
    {simulationID: '45675', colorName:'Green'},
    {simulationID: '45677', colorName:'default'},
    {simulationID: '45673', colorName:'red'},
    {simulationID: '45680', colorName:'Green'},
    {simulationID: '45678', colorName:'default'}
]

我要这样排序:

var arrayAfterSort = [
    {simulationID: '45679', colorName:'Green'},
    {simulationID: '45675', colorName:'Green'},
    {simulationID: '45680', colorName:'Green'},
    {simulationID: '45672', colorName:'red'},
    {simulationID: '45673', colorName:'red'},
    {simulationID: '45676', colorName:'yellow'},
    {simulationID: '45677', colorName:'default'},
    {simulationID: '45678', colorName:'default'}
]

所以基本上我想按照以下顺序对数组进行排序。首先是绿色,然后是红色,然后是黄色,然后默认。因此,排序顺序为绿色,红色,黄色,默认

3 个答案:

答案 0 :(得分:2)

您可以简单地使用Arrays.sort()并使用order数组按照order数组指定的顺序对数组进行排序。

尝试以下操作:

var arrayBeforeSort = [ {simulationID: '45679', colorName:'Green'}, {simulationID: '45672', colorName:'red'}, {simulationID: '45676', colorName:'yellow'}, {simulationID: '45675', colorName:'Green'}, {simulationID: '45677', colorName:'default'}, {simulationID: '45673', colorName:'red'}, {simulationID: '45680', colorName:'Green'}, {simulationID: '45678', colorName:'default'} ];

var order = ["Green","red","yellow","default"];
 
arrayBeforeSort.sort((a,b)=> order.indexOf(a.colorName) - order.indexOf(b.colorName));
 
console.log(arrayBeforeSort);

答案 1 :(得分:2)

您可以指定诸如sortOrder之类的对象来提及排序值的数值,以便可以在sort()函数内使用它们:

var arrayBeforeSort = [
    {simulationID: '45679', colorName:'Green'},
    {simulationID: '45672', colorName:'red'},
    {simulationID: '45676', colorName:'yellow'},
    {simulationID: '45675', colorName:'Green'},
    {simulationID: '45677', colorName:'default'},
    {simulationID: '45673', colorName:'red'},
    {simulationID: '45680', colorName:'Green'},
    {simulationID: '45678', colorName:'default'}
];
var sortOrder = {
  'Green': 1,
  'red' : 2,
  'yellow' : 3,
  'default' : 4
};

arrayBeforeSort.sort(function(a, b){
  return sortOrder[a.colorName] - sortOrder[b.colorName];
});
console.log(arrayBeforeSort);

答案 2 :(得分:1)

首先,根据所需结果定义颜色的值。从那里,您可以进行比较。

var colorArray = [];
colorArray['Green'] = 0;
colorArray['red'] = 1;
colorArray['yellow'] = 2;
colorArray['default'] = 3;
console.log(arrayBeforeSort.sort(function(a,b){
    return colorArray[a.colorName] > colorArray[b.colorName];
}));