match two sets of arrays containing rgb color values using if/else

42 views Asked by At

So I can create an array with rgb color values such as:

var atomArr = ['rgb(255, 255, 255)', 'rgb(255, 34, 0)', 'rgb(255, 34, 0)'];

With out going into details, I can even assign an object's background-color with a value from the array.

So why can't I take two similar arrays and check if both of them match (ordered match not necessary, but both arrays must contain the same values)?

In the example below, both arrays have the exact same values (not in order), but always triggers false.

var h2o = ['rgb(255, 255, 255)', 'rgb(255, 34, 0)', 'rgb(255, 34, 0)'];
function Check(A) {
    var atomArr = ['rgb(255, 34, 0)', 'rgb(255, 255, 255)', 'rgb(255, 34, 0)'];
    var i, j;
    var totalmatches = 0;
    for (i = 0; i < atomArr.length; i++) {
     for (j = 0; j < A.length; ++j) {
      if (atomArr[i] === A[j]) {
       totalmatches++;
      }
     }
    }
    if (totalmatches == 3) {
     console.log("true");
    } else {
     console.log("false");
    }
}

Check(h2o);

1

There are 1 answers

5
Ele On BEST ANSWER

This approach uses the function reduce to sum matches.

var h2o = ['rgb(255, 255, 255)', 'rgb(255, 34, 0)', 'rgb(255, 34, 0)'];
function Check(A) {
    var atomArr = ['rgb(255, 34, 0)', 'rgb(255, 255, 255)', 'rgb(255, 34, 0)'];
    var checked = true;
    A.forEach((r) => {
      if (!checked) return;
      
      var count = A.reduce((a, c) => a + (c === r ? 1 : 0), 0);
      var outerCount = atomArr.reduce((a, c) => a + (c === r ? 1 : 0), 0);
      
      checked = checked && count === outerCount;
    });
    
    console.log(checked);
}

Check(h2o);

for-loop

var h2o = ['rgb(255, 255, 255)', 'rgb(255, 34, 0)', 'rgb(255, 34, 0)'];
function Check(A) {
    var atomArr = ['rgb(255, 34, 0)', 'rgb(255, 255, 255)', 'rgb(255, 34, 0)'];
    var checked = true;
    for (var i = 0; i < A.length; i++) {
      if (!checked) break;
      
      var r = A[i];
      var count = A.reduce((a, c) => a + (c === r ? 1 : 0), 0);
      var outerCount = atomArr.reduce((a, c) => a + (c === r ? 1 : 0), 0);
      
      checked = checked && count === outerCount;
    };
    
    console.log(checked);
}

Check(h2o);