如何根据对象中的另一个数组过滤数组?
How to filter an array according another array in object?
我有一个数组:
const arr = [
{id: 1, text: "hello", likes: [1,2,5]},
{id: 2, text: "text", likes: []},
{id: 3, text: "example", likes: [1]}
]
如何根据 likes 数组的长度过滤它,即数组应该是这样的:
const arr = [
{id: 1, text: "hello", likes: [1,2,5]},
{id: 3, text: "example", likes: [1]},
{id: 2, text: "text", likes: []},
]
您可以使用带有参数 a,b
的 Array.prototype.sort()
并比较 likes
属性
的长度 属性
在此处阅读更多内容:
javascript Array.prototype.sort
const arr = [
{id: 1, text: "hello", likes: [1,2,5]},
{id: 2, text: "text", likes: []},
{id: 3, text: "example", likes: [1]}
]
arr.sort(function(a,b) {
return b.likes.length - a.likes.length;
});
for(let a = 0; a < arr.length; a++){
console.log(arr[a]);
}
我有一个数组:
const arr = [
{id: 1, text: "hello", likes: [1,2,5]},
{id: 2, text: "text", likes: []},
{id: 3, text: "example", likes: [1]}
]
如何根据 likes 数组的长度过滤它,即数组应该是这样的:
const arr = [
{id: 1, text: "hello", likes: [1,2,5]},
{id: 3, text: "example", likes: [1]},
{id: 2, text: "text", likes: []},
]
您可以使用带有参数 a,b
的 Array.prototype.sort()
并比较 likes
属性
在此处阅读更多内容: javascript Array.prototype.sort
const arr = [
{id: 1, text: "hello", likes: [1,2,5]},
{id: 2, text: "text", likes: []},
{id: 3, text: "example", likes: [1]}
]
arr.sort(function(a,b) {
return b.likes.length - a.likes.length;
});
for(let a = 0; a < arr.length; a++){
console.log(arr[a]);
}