在数组上过滤n次

时间:2018-05-14 14:02:17

标签: javascript arrays filter

我想重新创建在线商店所拥有的过滤器,如果有人想选择说“T恤”'并且在'绿色'。显然很容易。但是,如果他们选择多种颜色,我该怎么办呢?

我知道我可以像这样链接:colors.filter(col => col.name =='green' || col.name =='black'),但是如果我想要选择10种颜色或20种颜色,那么目前这种颜色不是很容易扩展。我可以用某种方式映射颜色然后过滤吗?

我尝试了这个,但它不起作用:

colors = ['black', 'red']
col = [{name: 'green'}, {name: 'black'}, {name: 'red'}]
colors.forEach((c) => col.filter((ca) => ca.name === c))`

5 个答案:

答案 0 :(得分:5)

您可以使用Set

let filterColors = new Set();
filterColors.add('green');
filterColors.add('black');

colors.filter(col => filterColors.has(col.name));

答案 1 :(得分:4)

  

如果他们选择多种颜色,我该怎么做?

您可以使用includes()indexOf()方法。

colors = ['black', 'red']
col = [{name: 'green'}, {name: 'black'}, {name: 'red'}]
var selected = col.filter(prod => colors.includes(prod.name))
console.log(selected);

答案 2 :(得分:0)

您可以为最终结果创建一个名为selectedColor的新数组,以便以匹配的颜色推送对象。

colors = ['black', 'red'];
col = [{name: 'green'}, {name: 'black'}, {name: 'red'}];
var selectedColor = [];
colors.forEach((c) => col.filter((ca) => {
   if(ca.name === c){
     selectedColor.push(ca);
   }
}));
console.log(selectedColor);

使用indexOf()

colors = ['black', 'red']
col = [{name: 'green'}, {name: 'black'}, {name: 'red'}]
var selected = col.filter(prod => colors.indexOf(prod.name) !== -1)
console.log(selected);

  

强烈建议使用indexOf(),因为includes()在IE浏览器中不起作用。

答案 3 :(得分:0)

您可以使用array.includes:

colors = ['black', 'red']
cols = [{name: 'green'}, {name: 'black'}, {name: 'red'}];

var filtered = cols.filter(c => colors.includes(c.name));
console.log(filtered);

答案 4 :(得分:0)

您应该使用filterincludes



const colors = ['black', 'red']
const col = [{name: 'green'}, {name: 'black'}, {name: 'red'}]
let filtered = col.filter(ca => colors.includes(ca.name))
console.log(filtered)