Javascript,在跳过不匹配的索引时按顺序比较两个数组

时间:2016-06-17 01:34:07

标签: javascript arrays

我有两个数组:

var arr1 = [1,2,3,4,5]
var arr2 = [7,1,8,2,12,3,4,28,5]

我需要通过arr2寻找与arr1的匹配,但它必须按顺序排列(1,2,3,4,5)。正如您在arr2中看到的那样,订单确实存在,但介于两者之间。

[7,的 1 下,如图8所示, 2 下,12,的 3 < / EM> 4 下,28的 5

我有大约50个类似于arr2的数组,所以我需要查看每个数组,当我找到匹配时,将其推送到“结果”对象。但小问题是某些阵列不会有整个匹配,可能只有1,2,3或任何搜索变体。此外,如果我正在搜索的数组不是有序的,(IE:从2,3,4开始)完全跳过它。

我们的想法是循环遍历这些数组,当我找到匹配项时,将结果数组添加到结果数组中。

例如,使用arr1作为搜索,请浏览这些数组:

[7,的 1 下,如图8所示, 2 下,12,的 3 < / EM> 4 下,28的 5 ], [7,的 1 下,如图8所示, 2 下,12,的 3 4 ], [7,8,的 1 2 ], [ 1 2 3 ] < / p>

并得到一个看起来像这样的结果(搜索到的内容的字典,以及找到的内容的数量):

{1:4, 2:4, 3:3, 4:2, 5:1}

我尝试了一堆for循环,但是我无法弄清楚如何跳过我不想要的数字,并继续进行下一次迭代,同时将结果保存到字典对象中。

4 个答案:

答案 0 :(得分:1)

基本上就是这样:

var needle = [1,2,3,4,5]
var collection = [[7,1,8,2,12,3,4,28,5], [7,1,8,2,12,3,4], [7,8,1,2], [1,2,3]]

// start with an object
var results = {}
// populate object with zeros
needle.forEach(function (i) { results[i] = 0 })
// define an index to iterate through collection
var i = 0
// define an index to conditionally iterate through "arr1"
var j = 0
// define an index to iterate through collection arrays 
var k = 0
// define surrogate for the arrays in the collection
var arr

while (i < collection.length) {
  
  // get collection array
  arr = collection[i]
  // reset the indices
  j = 0
  k = 0

  while (k < arr.length) {
    // if same element on needle is in a collection array 
    if (needle[j] === arr[k]) {
      // save it in an object starting at 1
      results[needle[j]]++
      j++ // increment needle
    }
    k++ // increment array in collection
  }
  i++ // increment collection
}

console.log(results) // {1:4, 2:4, 3:3, 4:2, 5:1}

我希望有所帮助!

答案 1 :(得分:1)

&#13;
&#13;
let list = [[7,1,8,2,12,3,4,28,5], [7,1,8,2,12,3,4], [7,8,1,2], [1,2,3]];
let search = [1, 2, 3, 4, 5];

// Initialize result with zeros:
let result = search.reduce((result, next) => {
  result[next] = 0;
  return result;
}, {});

// Increment result for items found:
list.forEach(array => {
  for (let i = 0, j = 0; i < array.length && j < search.length; ++i) {
    if (array[i] == search[j]) {
      ++result[search[j]];
      ++j;
    }
  }
});

console.log(result);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

var orign = [1,2,3,4,5];
var arr = [[7,1,8,2,12,3,4,28,5], [7,1,8,2,12,3,4], [7,8,1,2], [1,2,3]];

//temp result
var arrTmp = [];

for (var x in arr){
  var match = 0;
  var mis = 1;
  var curIndex = 0;
  var cur = orign[curIndex];
  var arrTmpX = [];
  for(var y in arr[x]){
    if(arr[x][y] !== cur){
      mis=1;
    }else{
      //add match after mismatch
        arrTmpX.push(cur);
      curIndex++
      cur = orign[curIndex];
    }
  }
  arrTmp.push(arrTmpX);
}

//calc result
var result = {};
for (var x in orign){
  result[orign[x]] = 0;
  for(var y in arrTmp){
    if(arrTmp[y].length>x)result[orign[x]]++;
  }
}

console.log(result);

这是有效的

答案 3 :(得分:0)

var arr1 = [1,2,3,4,5];

var arr2 = [7,1,8,2,12,3,4,28,5];


function givenTwoArrays(a,b, obj){
    var obj = obj || {};
    var cond = true;

    function otherMatch(indexFound,elementFound){
        var indexOnA = a.indexOf(elementFound);
        return a.some(function(ele, idx){
            if(idx > indexOnA)
                 return b.some(function(bele,bidx){
                    return ele == bele && bidx < indexFound;
                });
        });


    }


    a.map(function(aele,idx){
        if(cond){
            var indexFound = b.findIndex(function(bele){
                return aele == bele;
            });
            if(typeof indexFound !== 'undefined'){
                if(!otherMatch(indexFound,aele)){
                    if(typeof obj[aele] !== 'undefined')
                        obj[aele]++;
                    else{
                        obj[aele] = 1;
                    }
                } else {
                    cond = false;
                }
            }else
                cond = false;
        }

    });

    return obj;
}
console.log("first pass");
console.log(givenTwoArrays(arr1,arr2))
console.log("second pass");
console.log(givenTwoArrays(arr1,arr2,{
  "1": 1,
  "2": 1,
  "3": 1,
  "4": 1,
  "5": 1
}));

我认为这会起作用,只需要添加一点递归!