使用filter和sort-javascript将元素放在数组的最前面
我有一个对象数组,我想在其中找到某些元素,并将它们放在数组的开头或后面。我开始使用find函数,它工作了,但现在因为可以有多个元素,我切换到filter函数。然而,现在它停止了工作,我如何修复这个问题 输入示例:使用filter和sort-javascript将元素放在数组的最前面,javascript,sorting,filter,Javascript,Sorting,Filter,我有一个对象数组,我想在其中找到某些元素,并将它们放在数组的开头或后面。我开始使用find函数,它工作了,但现在因为可以有多个元素,我切换到filter函数。然而,现在它停止了工作,我如何修复这个问题 输入示例: colors= [ {name: "green", popular: true}, {name: "yellow", popular: false}, {name: "red", popular: true}
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 red变量返回一个数组,而不是像find这样的对象,您可以将红色部分排序到顶部
const
颜色=[{name:“绿色”,流行:真},{name:“黄色”,流行:假},{name:“红色”,流行:真},{name:“黑色”,流行:真},{name:“红色”,流行:真}];
colors.sort((a,b)=>(b.name==“red”)-(a.name==“red”);
控制台日志(颜色)
您可以使用filter()
两次,并使用spread运算符对数组进行正确排序
const colors=[
{name:“green”,popular:true},
{name:“yellow”,流行:false},
{name:“red”,popular:true},
{name:“black”,popular:true},
{名称:“红色”,流行:真}
]
常量res=[…colors.filter(x=>x.name==“红色”),…colors.filter(x=>x.name!=“红色”);
console.log(res)
您可以使用reduce
和unsheit
。在reduce callback内部,放入所有没有红色
名称的元素,并在另一个数组中放入具有红色名称的元素。使用unshift
将元素添加到开头
let colors=[{
名称:“绿色”,
流行:真的
},
{
名称:“黄色”,
流行:错
},
{
名称:“红色”,
流行:真的
},
{
名称:“黑色”,
流行:真的
},
{
名称:“红色”,
流行:真的
}
];
设colArr=[];
让arr=颜色。减少((acc,curr)=>{
如果(curr.name=='red'){
colArr.推力(当前)
}否则{
附件推送(当前)
}
返回acc;
}, []);
colArr.forEach((项目,索引)=>{
到货取消提货(项目)
});
console.log(arr)
如果您只想以与以前相同的方式获取对象,为什么不检查数组中是否有项,如果有,则获取数组中的第一个元素?如果(red.length>0)。如果您只想在红色上排序,那么您可以在不使用过滤器的情况下进行排序,并且只使用您已经在做的排序。。。