0

I've seen this question and this one but none of the answers seem to work for me.

The idea is to figure out what is inside colors1 and colors2, and retain only matching colors into another array: 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);

In the example above, colorsPicked contains: red, blue, yellow.

What I need to get as a result is only the colors that match between colors1 and colors2. That is to say, colorsPicked should return: red

if colors1 contains red, blue, yellow and color2 contains red, blue, black then colorsPicked should return: red, blue

How does one do this?

Sweepster
  • 1,829
  • 4
  • 27
  • 66
  • `colors1.concat(colors2).includes(el)` is always true because `colors1.concat(colors2)` contains everything from both arrays. Use this: `const colorsPicked = colors1.filter( color => colors2.includes( color ) )`. – Paul Feb 24 '19 at 20:36
  • There's lots of answers already, but I think what you're struggling with here is not JavaScript, but logic and set theory which are very important parts of computer science. I'd advice to look up "union" and "intersection" of sets on Wikipedia for a start. – Forketyfork Feb 24 '19 at 20:43

3 Answers3

0

simply check if the values of one are also in the other.

const colors1 = ["red", "blue"];
const colors2 = ["red", "yellow"];   

const colorsPicked = colors2.filter(el => colors1.includes(el));
console.log(colorsPicked);
Snowmonkey
  • 3,716
  • 1
  • 16
  • 16
0

Simply check the index of the element in another array

const colors1 = ["red", "blue"];
const colors2 = ["red", "yellow"];  
console.log(colors1.filter((e)=>colors2.indexOf(e)>-1))
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

You can use indexOf() while filtering color1 to see if value in color2 like this

const colors1 = ["red", "blue"];
const colors2 = ["red", "blue"];   
const colorsPicked = colors1.filter(function(el){
    if(colors2.indexOf(el)>-1){return el;}
});
console.log(colorsPicked);
Osama
  • 2,912
  • 1
  • 12
  • 15