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

标签 javascript arrays sorting

我有一个数组:

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/

相关文章:

java - 字符串数组字数统计

algorithm - 用于螺母和 bolt 匹配的最坏情况 NlogN 算法

javascript - jquery中的自定义自动完成功能

javascript - 如何将变量传递给d3中的事件监听器方法

javascript - 从 Firefox 扩展检测 JS API 调用

c++ - 实现外部归并排序

Mysql对字符串数据的列排序

javascript - jQuery 和 ASP.Net 资源和陷阱

名为 "AB"的结构可以包含 AB 数组吗?

C#:有没有办法确定一个范围内的元素是否为空?