如何在 JS 中根据对象 属性 对数组内的项目进行排序
How to order items inside array based on object property in JS
我有一个对象数组:
[
{
Name:
likes:[]
...
}
]
我需要先排序没有 likes 的对象,其中 likes 是未定义的,然后是 likes 数组中只有 1 个项目的对象,然后是 likes 数组中有更多项目的其他对象。怎样才能正确完成?
function sortBy(selector) {
const cmp = (a, b) => (selector(a) - selector(b));
return list => list.sort(cmp);
}
const data = [{ Name: "Foo", likes:[{}, {}, {}] }, { Name: "Bar", likes:[{}] }, { Name: "Baz", likes:[{}] }, { Name: "Plugh", likes:[] }];
const sortByLikes = sortBy(({ likes }) => likes.length);
console.log(sortByLikes(data));
var temp = [
{
Name: "abc",
likes: [1,2,3]
},
{
Name: "ac",
likes:[1]
},
{
Name: "bc",
likes:null
},
{
Name: "c",
likes:[1,2,3,4]
}
];
temp = temp.sort((a, b) => {
if(a.likes === undefined || a.likes === null)
return -1;
else if(b.likes === undefined || b.likes === null)
return 1;
else{
return a.likes.length - b.likes.length;
}
});
console.log(temp);
我有一个对象数组:
[
{
Name:
likes:[]
...
}
]
我需要先排序没有 likes 的对象,其中 likes 是未定义的,然后是 likes 数组中只有 1 个项目的对象,然后是 likes 数组中有更多项目的其他对象。怎样才能正确完成?
function sortBy(selector) {
const cmp = (a, b) => (selector(a) - selector(b));
return list => list.sort(cmp);
}
const data = [{ Name: "Foo", likes:[{}, {}, {}] }, { Name: "Bar", likes:[{}] }, { Name: "Baz", likes:[{}] }, { Name: "Plugh", likes:[] }];
const sortByLikes = sortBy(({ likes }) => likes.length);
console.log(sortByLikes(data));
var temp = [
{
Name: "abc",
likes: [1,2,3]
},
{
Name: "ac",
likes:[1]
},
{
Name: "bc",
likes:null
},
{
Name: "c",
likes:[1,2,3,4]
}
];
temp = temp.sort((a, b) => {
if(a.likes === undefined || a.likes === null)
return -1;
else if(b.likes === undefined || b.likes === null)
return 1;
else{
return a.likes.length - b.likes.length;
}
});
console.log(temp);