Compare two arrays

Hi, I have these two examples to compare two arrays with each other to find matches. I wanted to know which option would be more successful and readable.

const colorsOne = ["Blue", "Green", "Red"];
const colorsTwo = ["Blue", "Black"];
let color = false;

// First Example
for(i = 0; i < colorsOne.length; i++){
  const search = colorsTwo.indexOf(colorsOne[i]);
  if(search >= 0){
    color = true;
  }
}

// Second Example
for(i = 0; i < colorsOne.length; i++){
  for(j = 0; j < colorsTwo.length; j++){
    if(colorsOne[i] == colorTwo[j]){
      color = true;
    }
  }
}

1 Like

I’m not sure which one is more successful, but in terms of readability, the first example is clearer for me.

Nested for makes my brain ache; though in this case, it’s simple so it’s not that bad

I have the same problem with the nested for, but I still can’t decide

You might want to look at the includes higher order function

Thanks, you save me a few lines of code.

I will use it that way

for(k = 0; k < colorsOne.length; k++){
  color = colorsOne.includes(colorsTwo[k]);
}