在数组数组中查找缺少的数组

时间:2013-07-27 11:50:23

标签: javascript arrays

我需要在“数组数组”中找到一个缺少的数组。我开始在下面找到这个函数(在StackOverflow上):

function findDeselectedItem(CurrentArray, PreviousArray) {

   var CurrentArrSize = CurrentArray.length;
   var PreviousArrSize = PreviousArray.length;
   var deselectedItem = [];

   // loop through previous array
   for(var j = 0; j < PreviousArrSize; j++) {

      // look for same thing in new array
      if (CurrentArray.indexOf(PreviousArray[j]) == -1)
         deselectedItem.push(PreviousArray[j]);

   }

   return deselectedItem;
}

如果你做了这样的事情,这个工作正常:

oldarray = ["hi", "ho", "hey"];
newarray = ["hi", "hey"];

使用findDeselectedItem(newarray, oldarray)会返回[“ho”]。

但是,我的内容如下:

oldarray = [["James", 17, 1], ["Olivia", 16, 0], ["Liam", 18, 1]];
newarray = [["Olivia", 16, 0], ["James", 17, 1]];

如何调整上面的函数,使其返回包含'Liam'的缺失数组。

谢谢

6 个答案:

答案 0 :(得分:2)

我会使用名称作为键来创建哈希。这将使寻找缺失的内容变得微不足道并且非常快。然后,您可以通过不每次重建哈希来优化方法,但只有在确实需要时才会优化。

var oldArray = [["James", 17, 1], ["Olivia", 16, 0], ["Liam", 18, 1]];
var newArray = [["Olivia", 16, 0], ["James", 17, 1]];

function findDeselectedItems(oldArray, newArray)
{
   var results = [];

   var hash = {};
   for (var i=0; i<newArray.length; i++) {          
      hash[newArray[i].join(',')] = true;
   }

   for (var i=0; i<oldArray.length; i++) {
      if (!hash[oldArray[i].join(',')]) {
        results.push(oldArray[i]);
      }   
   }

   return results;
}   

答案 1 :(得分:1)

问题可能是indexOf使用严格的平等。即如果'previous'数组中的一个项目在'current'数组中 ,它将报告它不在那里。

您必须自己迭代值(而不是使用indexOf)并检查数组是否包含“与'相同的内容(但不是字面上相同)数组。

即。如果我不能很好地解释自己,请看看这个;

['bob'] == ['bob']; //false
//therefore
[['bob']].indexOf(['bob']); //-1

答案 2 :(得分:0)

我希望这对你有帮助,

function findDeselectedItem(CurrentArray, PreviousArray) {

    var CurrentArrSize = CurrentArray.length;
    var PreviousArrSize = PreviousArray.length;
    var deselectedItem = [];

    // loop through previous array
    for(var j = 0; j < PreviousArrSize; j++) {
        var checkArray = PreviousArrSize[j];
        // loop through 2nd array to match both array

        for(var i = 0; i < CurrentArrSize; i++) {
            // look for same thing in new array
            if (CurrentArray[i].indexOf(checkArray) == -1)
                deselectedItem.push(CurrentArray[i]);

        }
    }
    return deselectedItem;
}

答案 3 :(得分:0)

@KarelG:很好而且快速的解决方案但不应该是var checkArray = PreviousArr[j];而不是var checkArray = PreviousArrSize[j];吗?

答案 4 :(得分:0)

function findDeselectedItem(CurrentArray, PreviousArray) {

    var CurrentArrSize = CurrentArray.length;
    var PreviousArrSize = PreviousArray.length;
    var deselectedItem = [];
    var selectedIndices = [];

  // loop through previous array
  for(var j = 0; j < PreviousArrSize; j++) {

   for(k=0; k < CurrentArrSize ; k++){
      if (CurrentArray[k].toString() === PreviousArray[j].toString()){
          selectedIndices.push(j);
          break;
      }

   }

 }

    for(var l = 0; l < PreviousArrSize; l++){
      if(selectedIndices.indexOf(l) === -1){
         deselectedItem.push(PreviousArray[l]);
      }
    }

      return deselectedItem;
}

答案 5 :(得分:0)

我认为您不能使用indexOf来比较两个数组。你需要更深入的比较。虽然这段代码可以用另一种方式编写,但您可以使用数组比较函数并使用Array.some()来过滤元素。这是一个示例和fiddle;

// Credit http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript
// attach the .compare method to Array's prototype to call it on any array
Array.prototype.compare = function (array) {
    // if the other array is a falsy value, return
    if (!array)
        return false;

    // compare lengths - can save a lot of time
    if (this.length != array.length)
        return false;

    for (var i = 0; i < this.length; i++) {
        // Check if we have nested arrays
        if (this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!this[i].compare(array[i]))
                return false;
        }
        else if (this[i] != array[i]) {
            // Warning - two different object instances will never be equal: {x:20} != {x:20}
            return false;
        }
    }
    return true;
}

function findDeselectedItem(CurrentArray, PreviousArray) {

    var CurrentArrSize = CurrentArray.length;
    var PreviousArrSize = PreviousArray.length;
    var deselectedItem = [];

    // loop through previous array
    for (var j = 0; j < PreviousArrSize; j++) {
        // look for same thing in new array
        CurrentArray.some(function (a, idx) {
            if(PreviousArray[j].compare(a) == false) {
                deselectedItem.push(PreviousArray[j]);
                return true;
            }
        });
    }

    return deselectedItem;
    }

var oldarray =[["James", 17, 1], ["Olivia", 16, 0], ["Liam", 18, 1]];
var newarray =[["Olivia", 16, 0], ["James", 17, 1]];

console.log(findDeselectedItem(newarray, oldarray));