查找数组

时间:2017-03-20 01:38:27

标签: javascript arrays

我需要检查传入的数值数组是否匹配一组数值数组的任何变化。我基本上只是坚持逻辑。

鉴于

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];

到目前为止,我的尝试无处可去,所以我把它减少到了这一点 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);

2 个答案:

答案 0 :(得分:2)

以下代码中的findCombo函数使用功能方法来解决您的问题。欢迎阅读有关Mozilla开发者网络上.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];

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

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

答案 1 :(得分:1)

您可以使用.findIndex().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]);