我正在尝试对该数组进行排序:
[
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
},
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
}
]
如您所见,有些对象没有parentId
。我需要将其放在顶部,其余按id
排序。
这是我的代码:
input.sort(function (a, b) {
if (typeof a.parentId === 'undefined'))
return -1;
else
return a.id - b.id;
});
虽然不起作用。可以这样做吗?
预期结果:
[
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
},
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
}
]
预先感谢
答案 0 :(得分:2)
我建议使用lodash js库
var arr = [
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
},
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
}
];
var sortedArr = _.orderBy(arr, 'parentId', 'desc');
console.log(sortedArr);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
答案 1 :(得分:1)
需要测试A和B并反转。如果A缺少道具,则使用-1,如果B使用+1
let arr = [{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
},
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
}
];
const sortPredicate = (a,b) => {
if (a.hasOwnProperty('parentId') === false) {
return -1;
} else if(b.hasOwnProperty('parentId') === false) {
return 1;
} else {
return a.id - b.id;
}
};
console.log(arr.sort(sortPredicate));