-3

I need a help with this code. I want to check if array matches to one of the combos (array should contain 3 numbers which one of the combos has). If matches should return true.

I tried to write code using indexOf and includes but I couldn't write it correctly. Can you please help me?

const arr1 = [2,3,5,8,1]// comparing should return true, matches combos[6] 
const arr2 = [3,1,4]    // comparing should return false
const arr3 = [1,2,4,3]  // comparing should return true ,matches combo[0]
const arr4 = [9,7,8]    // comparing should return true, matches combo[2]
const combos = [[1,2,3],[4,5,6],[7,8,9],[1,5,9],[3,5,7],[1,4,7],[2,5,8],[3,6,9]]
Chladziu
  • 11
  • 1
  • 2
    It would be good if you posted the code that isn't working so that you can be told where exactly it went wrong. –  Feb 06 '17 at 16:59
  • Those don't really match--you need to define specifically what "matching" means. – Dave Newton Feb 06 '17 at 16:59
  • Possible duplicate of [How to compare arrays in JavaScript?](http://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – Matvey Andreyev Feb 06 '17 at 17:00
  • By a "match", the OP seems to be saying that there's at least one array in `combos` where all the numbers are included in the array in question. –  Feb 06 '17 at 17:01
  • Chladziu: To make pretty simple work of it, you should look at the `.some()` method for the `combos` array, and the `.every()` method for testing each of its nested arrays. –  Feb 06 '17 at 17:02
  • squint thanks for help! – Chladziu Feb 06 '17 at 18:43

1 Answers1

0

I'm not sure if there's a better way using some callback and whatnot, but it works the old-fashioned way of going through the combos one by one and then checking each individual number if it's in the test set:

const arr1 = [2,3,5,8,1];
const arr2 = [3,1,4];
const arr3 = [1,2,4,3];
const arr4 = [9,7,8];
const combos = [[1,2,3],[4,5,6],[7,8,9],[1,5,9],[3,5,7],[1,4,7],[2,5,8],[3,6,9]]; 

function findCombo(combos, test)
{
    for (var i=0; i<combos.length; i++)
    {
        var ok=true;
        for (var k=0; k<combos[i].length; k++)
            if (test.indexOf(combos[i][k])<0) { ok=false; break; }
        if (ok) return true;
    }
    return false;
}

console.log(findCombo(combos, arr1));
console.log(findCombo(combos, arr2));
console.log(findCombo(combos, arr3));
console.log(findCombo(combos, arr4));
Wolfgang Stengel
  • 2,867
  • 1
  • 17
  • 22