jozenbasin
jozenbasin

Reputation: 2552

Find a combination of numbers in an array

I need to check if an incoming numerical array matches any variation of a set of numerical arrays. I am basically just stuck on the logic.

Given

var myData = [1, 201, 100]

Are these three numbers found in any order in the following pre-set combinations

var combo1 = [1, 100, 200]
var combo2 = [1, 101, 201]
var combo3 = [1, 100, 201]
var combo4 = [1, 101, 200];

My attempt so far is going nowhere so I've reduced it to this https://jsfiddle.net/0mvk9dj4/1/

var myData = [1, 201, 100];

var combo1 = [1, 100, 200]
var combo2 = [1, 101, 201]
var combo3 = [1, 100, 201]
var combo4 = [1, 101, 200];
var combos = [combo1, combo2, combo3, combo4];

function findCombo(data) {
  var found = false
  for (var i = 0; i < combos.length; i++) {
    var combo = combos[i];
    for (var x = 0; x < combo.length; x++) {
      for (var y = 0; y < data.length; y++) {
        if (data[y] === combo[x]) {
          found = true;
          break;
        } else {
          found = false;
        }
      }
    }
  }
  console.log("Found? " + found)
  return found;
}

findCombo(myData);

Upvotes: 0

Views: 80

Answers (2)

guest271314
guest271314

Reputation: 1

You can use .findIndex() or .filter(), .every(), .some()

var myData = [1, 201, 100];

var combo1 = [1, 100, 200]
var combo2 = [1, 101, 201]
var combo3 = [1, 100, 201]
var combo4 = [1, 101, 200];
var combos = [combo1, combo2, combo3, combo4];
var res = combos.filter(combo =>  combo.every(n => myData.some(curr => curr === n)));

console.log(res);

var res = combos.findIndex(combo =>  combo.every(n => myData.some(curr => curr === n)));

console.log(combos[res]);

Upvotes: 1

Onel Harrison
Onel Harrison

Reputation: 1334

The findCombo function in the code below uses a functional approach to solve your problem. Feel free to read more about the .every() and .some() methods on the Mozilla Developer Network.

var myData = [1, 201, 100];

var combo1 = [1, 100, 200];
var combo2 = [1, 101, 201];
var combo3 = [1, 100, 201];
var combo4 = [1, 101, 200];

var combos = [combo1, combo2, combo3, combo4];

function findCombo(data, combos) {
  return combos.some(function(combo) {
    return combo.every((item) => data.includes(item));
  });
}

console.log(findCombo(myData, combos));

Upvotes: 2

Related Questions