javascript - 按属性数组对对象数组进行排序

标签 javascript arrays sorting

我有一组像这样的对象:

var SkillBuddys = [
    {
        Property1: "1",
        Property2: "Test",
        Property3: "Data",
        Property4: [{},{},{}],
    }, {
        Property1: "2",
        Property2: "Test2",
        Property3: "Data2"
    }, {
        Property1: "3",
        Property2: "Test3",
        Property3: "Data3",
        Property4: [{},{}],
    }, {
        Property1: "4",
        Property2: "Test4",
        Property3: "Data4"
    }, {
        Property1: "5",
        Property2: "Test5",
        Property3: "Data5",
        Property4: [{}],
    }
];

我想在属性 4 上使用 javaScript 对其进行排序,所以如果对象具有属性 4 并包含一个数组。像这样:
var SkillBuddys = [
    {
        Property1: "1",
        Property2: "Test",
        Property3: "Data",
        Property4: [{},{},{}],
    }, {
        Property1: "3",
        Property2: "Test3",
        Property3: "Data3",
        Property4: [{},{}],
    }, {
        Property1: "5",
        Property2: "Test5",
        Property3: "Data5",
        Property4: [{}],
    }, {
        Property1: "2",
        Property2: "Test2",
        Property3: "Data2"
    }, {
        Property1: "4",
        Property2: "Test4",
        Property3: "Data4"
    }
];

如果属性 4 不存在,则返回“未定义”。如何使用 Array.Sort 对其进行排序?

最佳答案

你可以 sort数组使用 length属性(property)和||运算符(operator)。

var array = [ { Property1: "1", Property2: "Test", Property3: "Data", Property4: [{},{},{}], }, { Property1: "2", Property2: "Test2", Property3: "Data2" }, { Property1: "3", Property2: "Test3", Property3: "Data3", Property4: [{},{}], }, { Property1: "4", Property2: "Test4", Property3: "Data4" }, { Property1: "5", Property2: "Test5", Property3: "Data5", Property4: [{}], } ];

array.sort((a, b) => (b['Property4'] || []).length - (a['Property4'] || []).length);

console.log(array);

关于javascript - 按属性数组对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59375271/

相关文章:

javascript - Openlayers/Openstreetmap 背景是垂直条纹和压扁的

arrays - 通过属性将数组传递给 AngularJS 指令

javascript - 将对象属性转换为对象数组

C++数组结构

algorithm - 再分配算法

javascript - 为什么标签存在?

javascript - jQuery 定位非事件选项卡内的 anchor 标记

javascript - 在 React 组件中渲染 HTML DOM 节点

c++ - 如何有效地*几乎*对列表进行排序?

java - 如何去掉排序整数末尾的零