skip to Main Content

I have two arrays with exact same values and index

const colors = ["#da9f64", "#f67dd1", "red", "gray"];
const colorsff = ["#da9f64", "#f67dd1", "red", "gray"];

I want to create a function that will do something particular IF either values or index of arrays match

something like this

function colorsMatch(){
if(colors.indexof() === colorsff.indexof()){
   someHtmlElement.classList.remove('d-none')
}
}

I tried everything i was able to look up

2

Answers


  1. You’ll need a loop of some kind:

    colors.forEach((color, i) => {
      if (colorsff[i] === color) {
        // do something
    })
    
    Login or Signup to reply.
  2. If your goal is to execute an action if all elements of two arrays match up, and you’re sure they have the same length, you could do something like this.

    const colors = ["#da9f64", "#f67dd1", "red", "gray"];
    const colorsff = ["#da9f64", "#f67dd1", "red", "gray"];
    const colors00 = ["#da9f64", "#f67dd1", "red", "err"];
    
    function colorsMatch(array1, array2) {
      const allMatch = array1.every((value, index) => {
        return array2[index] === value;
      });
      if (allMatch) {
        console.log("Do something");
      } else {
        console.log("Dont do anything");
      }
    }
    
    console.log("Matching original matching input");
    colorsMatch(colors, colorsff);
    
    console.log("Matching err input");
    colorsMatch(colors, colors00);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search