使用filter和sort将元素放在数组的开头 - javascript

4

我有一个对象数组,我想要找到其中的某些元素并将它们放在数组的开头或结尾。一开始我使用了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 一样返回一个对象。


如果你只是想以前的方式获取一个对象,为什么不检查数组中是否有项目,如果有,就取数组中的第一个元素呢?如果(red.length > 0) ...对red[0]进行一些操作。如果你只想按红色排序,那么你可以不使用过滤器,直接使用已经在使用的排序方法... - Toby
3个回答

7

您可以将红色部分排在顶部。

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);


2
你可以使用filter()两次并使用展开操作符将数组正确排序。

const colors= [
   {name: "green", popular: true},
   {name: "yellow", popular: false},
   {name: "red", popular: true},
   {name: "black", popular: true},
   {name: "red", popular: true}
]

const res = [...colors.filter(x => x.name === "red"), ...colors.filter(x => x.name !== "red")];
console.log(res)


0

你可以使用reduceunshift。在reduce的回调函数中,将所有没有red名称的元素放入一个数组中,并将有red名称的元素放入另一个数组中。使用unshift将这些元素添加到数组开头。

let colors = [{
    name: "green",
    popular: true
  },
  {
    name: "yellow",
    popular: false
  },
  {
    name: "red",
    popular: true
  },
  {
    name: "black",
    popular: true
  },
  {
    name: "red",
    popular: true
  }
];

let colArr = [];

let arr = colors.reduce((acc, curr) => {

  if (curr.name === 'red') {
    colArr.push(curr)
  } else {
    acc.push(curr)
  }
  return acc;
}, []);

colArr.forEach((item, index) => {
  arr.unshift(item)
});

console.log(arr)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接