我有一个数组:
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}
},]
需要对这些数组进行排序,其中存在数据的位置将位于顶部,然后是其他。 最终排序结果将是 -
[{ID:1,name: one,data: {}},
{ID:3,name: three,data: {}},
{ID:5,name: five,data: {}},
{ID:2,name: two},
{ID:4,name: four}]
最佳答案
您可以使用属性的 bool 值的增量。
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; }
另一个对 key 有压力的版本可能是检查是否存在。
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; }
关于javascript - 使用默认的 .sort() 对 JavaScript 中所需的数组对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39766226/