JavaScript中需要使用默认的.sort()对数组对象进行排序

sorting for array object needed in JavaScript using default .sort()

本文关键字:数组 对象 排序 sort 默认 JavaScript      更新时间:2023-09-26

我有一个数组:

var array = [
{ID : 1,
Name : one,
data : {more info here}
},
{ID : 2,
Name : two
},
{ID : 3,
Name : three,
data : {more info here}
},
{ID : 4,
Name : four
},
{ID : 5,
Name : five,
data : {more info here}
},]

需要对这些数组进行排序,数据存在的地方将是top,然后是other。最终排序结果将是-

[{ID:1,name: one,data: {}},
{ID:3,name: three,data: {}},
{ID:5,name: five,data: {}},
{ID:2,name: two},
{ID:4,name: four}]

您可以使用属性的boolen值的增量

var array = [{ ID: 1, Name: 'one', data: {} }, { ID: 2, Name: 'two' }, { ID: 3, Name: 'three', data: {} }, { ID: 4, Name: 'four' }, { ID: 5, Name: 'five', data: {} }];
array.sort(function (a, b) {
    return !a.data - !b.data;
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

另一个强调键的版本可能是检查是否存在。

var array = [{ ID: 1, Name: 'one', data: {} }, { ID: 2, Name: 'two' }, { ID: 3, Name: 'three', data: {} }, { ID: 4, Name: 'four' }, { ID: 5, Name: 'five', data: {} }];
array.sort(function (a, b) {
    return ('data' in b) - ('data' in a);
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

从问题中不清楚,在期望的排序中唯一重要的是data属性的存在与否。期望的"最终排序结果"显示数据首先按data的存在或不存在排序,然后按ID在这些组中的升序排序。按ID排序可能仅仅是开始数组顺序的一个工件,而不是问题的必需部分。另一方面,可能需要先按data排序,然后再按ID排序。

其他解决方案要么根本不基于ID (Nina Scholz的答案)进行排序,要么同时通过dataID进行排序,但根据输入数组(Rajesh的答案)错误地进行排序。两者都依赖于输入数组的顺序来提供所需的结果数组。

下面的代码将首先根据data的存在与否对数组进行排序,然后根据这两个子组中的ID对数组进行排序。

对原先提供的输入数组进行排序:

var array = [{ ID: 1, Name: 'one', data: {} }, { ID: 2, Name: 'two' }, { ID: 3, Name: 'three', data: {} }, { ID: 4, Name: 'four' }, { ID: 5, Name: 'five', data: {} }];
array.sort(function(a, b) {
  if(a.data && !b.data) {
    // a has data, b does not have data, a is first
    return -1;
  }
  if(!a.data && b.data) {
    // a does not have data, b does have data, b is first
    return 1;
  }
  // a and b either both have data, or both don't have data. Sort the smaller ID first.
  return a.ID - b.ID;
});
console.log(array)

下面是相同的排序,从Rajesh更新的答案中使用的输入数组稍微修改。该答案中的数组已被修改为将ID:4,更改为ID:41,。使用修改后的输入数组,Rajesh的排序将产生错误的结果。此代码将按dataID对其进行正确排序。

var array=[{ID:1,Name:"one",data:{"more info here":"something"}},{ID:2,Name:"two"},{ID:30,Name:"Thirty",data:{"more info here":"something"}},{ID:41,Name:"four"},{ID:5,Name:"five",data:{"more info here":"something"}},{ID:40,Name:"fourty",data:{"more info here":"something"}},{ID:300,Name:"threeHundred",data:{"more info here":"something"}},{ID:20,Name:"twenty"},{ID:3e3,Name:"threeThousand",data:{"more info here":"something"}}];
array.sort(function(a, b) {
  if(a.data && !b.data) {
    // a has data, b does not have data, a is first
    return -1;
  }
  if(!a.data && b.data) {
    // a does not have data, b does have data, b is first
    return 1;
  }
  // a and b either both have data, or both don't have data. Sort the smaller ID first.
  return a.ID - b.ID;
});
console.log(array)