我有一个对象数组,我想在其中找到某些元素并将它们放在开头或数组中。我开始通过使用 find 功能来做这件事,但现在因为可以有多个元素我切换到 filter 功能,但是现在它停止工作了,我该如何解决这个问题?
输入示例:
colors= [
{name: "green", popular: true},
{name: "yellow", popular: false},
{name: "red", popular: true},
{name: "black", popular: true},
{name: "red", popular: true}
]
功能:sort(colors) {
let red= colors.filter(color=> colors.name === "red")
if(red){
colors.sort(function(x,y){ return x == red? -1 : y == red? 1 : 0; });
}
return colors
}
预期输出:colors= [
{name: "red", popular: true},
{name: "red", popular: true},
{name: "green", popular: true},
{name: "yellow", popular: false},
{name: "black", popular: true}
]
通过使用过滤器红色变量返回一个数组而不是像 find 这样的对象
最佳答案
您可以将红色部分排序到顶部。
const
colors= [{ name: "green", popular: true }, { name: "yellow", popular: false }, { name: "red", popular: true }, { name: "black", popular: true }, { name: "red", popular: true }];
colors.sort((a, b) => (b.name === "red") - (a.name === "red"));
console.log(colors);
关于javascript - 使用过滤器和排序将元素放在数组的开头 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63789070/