簡體   English   中英

比較多個數組的數組元素

[英]compare elements of array of many arrays

我試圖遍歷一個數組數組,並將元素相互比較,以找到公共元素。 所以假設我們有var arr = [[1,2,3],[4,2,5]]; 我想首先比較 [i][i] 和 [i+1][i]、[i][i+1] 和 [i+1][i+1] 和 [i][i+2] 和[i+1][i+2] 等等。 這是我的代碼:

function sym(args) {
  var fullArr = [];
  var finalArr = [];
  // store the arguments inside a single array
  for (var count = 0; count < arguments.length; count ++) {
    fullArr[count] = arguments[count];
  }
  // loop through finalArr[];
  for (var i = 0; i < fullArr.length; i++) {
    if (fullArr[i][i] == fullArr[i++][i++]) {
      // if the element matches (it is a common element)
      // store it inside finalArr
      finalArr[i] = fullArr[i];
    }
  }
  return finalArr;
}

sym([1, 2, 3], [5, 2, 1, 4]);

問題:當我運行代碼而不是包含匹配元素的數組時,我得到一個空數組

您首先必須遍歷一個數組並查看另一個數組是否包含您指定的值。

我的答案類似於嵌套的 for 循環,其中包含方法正是這樣做的。 它接受一個元素作為參數,並檢查調用它的數組是否包含該元素。 為了做到這一點,它必須在最壞的情況下遍歷數組中的所有元素。

我的回答還假設您只想計算一次重復的匹配項。

 function sym(args) { var fullArr = []; var finalArr = []; // store the arguments inside a single array for (var count = 0; count < arguments.length; count ++) { fullArr[count] = arguments[count]; } // loop through finalArr[]; //since you are comparing only two arrays in this //example you just have to iterate over each element in the first array aka fullArr[0] and //check if each element "e" is also in the second array aka fullArr[1] //AND that your final output array does not already contain it. //If both of these are true then we push the element to the output array. fullArr[0].forEach(function(e){ if(fullArr[1].includes(e) && !finalArr.includes(e)) finalArr.push(e); }); return finalArr; } sym([1, 2, 3], [5, 2, 1, 4]);

但是,如果你想檢查一個特定元素是否存在於一個長度為 n 的數組的所有集合中,那么我會提出這樣的建議:

 function sym(args) { var fullArr = []; var finalArr = []; // store the arguments inside a single array for (var count = 0; count < arguments.length; count ++) { fullArr[count] = arguments[count]; } var newArr = fullArr[0].reduce( function(prev, e1) { if(prev.indexOf(e1) < 0 && fullArr.every( function(arr){ return arr.indexOf(e1) > -1; })){ return [...prev, e1]; }else{ return prev; }; },[]); alert(newArr); return newArr; } sym([1,1, 2, 3,4], [5, 2, 1, 4], [4,1,2, 5]);

您可以迭代第一個數組並檢查它的任何值是否與所有其他數組相同。

function sym() {
    var common = [];
    for (var i=0; i<arguments[0].length; i++) {
        var isCommon = common.indexOf(arguments[0][i]) === -1; // first check if its not already exists in the common array
        for (var j=1; j<arguments.length && isCommon; j++) {
            isCommon = arguments[j].indexOf(arguments[0][i]) > -1
        }
        if (isCommon) common.push(arguments[0][i])
    }
    return common;
}

當然,您可以通過迭代最小數組來改進它。

在您的代碼中,當以下行執行時,您還會增加i的值,這是您的控制變量:

if (fullArr[i][i] == fullArr[i++][i++])

因此,這就是您的i變量在每次迭代中遞增的方式:

迭代#1: i = 0

迭代#2: i = 3 - 你從我上面提到的那一行得到 i+2,從你在 for 循環的最終條件中指定的增量中得到 +1

因此,即使在第一次迭代之后,您的函數也會在您的特定場景中返回一個空數組,因為您傳遞的是一個長度為 3 的數組,並且 for 循環在第一次迭代的i = 0之后結束。

即使循環繼續進行,它也會返回一個索引越界異常,因為您的長度為 3 的array[3]沒有array[3]元素。

例如,如果您只想比較兩個數組,就像在您的場景中一樣,您需要遍歷每個數組並比較它們的元素:

function sym(array1, array2) {
  var results = [];


  for (var i = 0; i < array1.length; i++) {
      for (var j = 0; j < array2.length; j++) {
          if(array1[i] === array2[j]) {
              if(results.indexOf(array1[i]) === -1) {
                  results.push(array1[i]);
              }
          }
      }
  }

  return results;
}

sym([1, 2, 3], [5, 2, 1, 4]);

我還構建了一個解決方案,它返回您作為函數參數提供的數組的交集,而不管有多少數組:

function sym(args) {
    var paramSet = Array.prototype.slice.call(arguments);
    var counterObject = {};
    var results = [];

    paramSet.forEach(function (array) {
        // Filter the arrays in order to remove duplicate values
        var uniqueArray = array.filter(function (elem, index, arr) {
            return index == arr.indexOf(elem);
        });


        uniqueArray.forEach(function (element) {
            if (Object.prototype.hasOwnProperty.call(counterObject, element)) {
                counterObject[element]++;
            } else {
                counterObject[element] = 1;
            }
        });
    });


    for (var key in counterObject) {
        if (counterObject[key] === paramSet.length) {
            results.push(parseInt(key));
        }
    }

    return results;

}

sym([1, 2, 3, 3, 3], [5, 2, 1, 4], [1, 7, 9, 10]);

對於我提供的示例,上面的代碼將返回[1] ,因為它是所有 3 個數組的交集。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM