我见过this question和this one,但似乎没有一个答案对我有效。
我们的想法是找出colors1和colors2中的内容,并只将匹配的颜色保留到另一个数组中: colorsPicked。
const colors1 = ["red", "blue"];
const colors2 = ["red", "yellow"];
const elements = ["red", "blue", "green", "yellow"];
const colorsPicked = elements.filter(el => colors1.concat(colors2).includes(el));
console.log(colorsPicked);在上面的示例中,colorsPicked包含:红色、蓝色、黄色。
作为结果,我需要得到的只是colors1和colors2之间匹配的颜色。也就是说,colorsPicked应该返回: red
如果colors1包含红色、蓝色、黄色,而color2包含红色、蓝色、黑色,则colorsPicked应返回:红色、蓝色
如何做到这一点?
发布于 2019-02-25 04:36:21
只需检查其中一个的值是否也在另一个中。
const colors1 = ["red", "blue"];
const colors2 = ["red", "yellow"];
const colorsPicked = colors2.filter(el => colors1.includes(el));
console.log(colorsPicked);
发布于 2019-02-25 04:36:22
只需检查另一个数组中元素的索引
const colors1 = ["red", "blue"];
const colors2 = ["red", "yellow"];
console.log(colors1.filter((e)=>colors2.indexOf(e)>-1))
发布于 2019-02-25 04:39:34
可以在过滤color1时使用indexOf()来查看color2中的值是否如下所示
const colors1 = ["red", "blue"];
const colors2 = ["red", "blue"];
const colorsPicked = colors1.filter(function(el){
if(colors2.indexOf(el)>-1){return el;}
});
console.log(colorsPicked);https://stackoverflow.com/questions/54856260
复制相似问题