我有一个对象数组,我想要找到其中的某些元素并将它们放在数组的开头或结尾。一开始我使用了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}
]
通过使用 filter,红色变量返回一个数组,而不像使用 find 一样返回一个对象。