【问题标题】:How to compare two arrays and then return the index of the difference?如何比较两个数组,然后返回差异的索引?
【发布时间】:2015-03-18 02:54:05
【问题描述】:

我有两个数组需要检查差异并返回差异的索引。

例如,我目前有两个数组,当输入值更改时会更新它们。只要输入中有新标签,newTags 数组就会更新,例如@testing。我需要将newTags 数组与oldTags 数组进行比较,并返回差异的索引。

我目前正在对两个数组进行字符串化并以这种方式比较它们,尽管它无法返回差异的索引。

var newTags = [];
var oldTags = [];

$input.on('keyup', function () {
    var newValue = $input.val();
    var pattern = /@[a-zA-Z]+/ig;
    var valueSearch = newValue.search(pattern);

    if (valueSearch >= 0) {
        newTags = newValue.match(pattern);

        if ((newTags + "") != (oldTags + "")) {
            //Need index of difference here
            console.log(newTags, oldTags);
        }

        oldTags = newTags;
    }
});

Working example

【问题讨论】:

  • 只在数组中搜索一个值?或搜索一个值,它与另一个数组的索引相同?
  • @floor - 例如,newTags 可以是 ["@testing", "@hello"],oldTags 可以是 ["@test", "@hello"]。因此,差异的索引为 0,因为数组中的第一个值不同。
  • 这让我更加困惑。
  • @floor - 哈哈哈,这可能是我的错。我要做的就是将newTagsoldTags 进行比较,然后返回差值数组中的位置。
  • 现在想想,一个简单的$.each 循环可能是最好的解决方案...

标签: javascript jquery arrays compare


【解决方案1】:

您可以使用过滤器同时查找不同的值和索引。

JSFiddle:https://jsfiddle.net/k0uxtnkd/

Array.prototype.diff = function(a) {
    var source = this;
    return this.filter(function(i) {
        if (a.indexOf(i) < 0) {
            diffIndexes.push(source.indexOf(i));
            return true;
        } else {
            return false;
        }
    });
};
var diffIndexes = [];
var newTags = ['a','b','c'];
var oldTags = ['c'];
var diffValues = newTags.diff(oldTags);
console.log(diffIndexes); // [0, 1]
console.log(diffValues); // ['a', 'b']

要将其转换为函数而不是将其添加到数组原型中: JSFiddle:https://jsfiddle.net/k0uxtnkd/1/

function arrayDiff(a, b) {
    return a.filter(function(i) {
        if (b.indexOf(i) < 0) {
            diffIndexes.push(a.indexOf(i));
            return true;
        } else {
            return false;
        }
    });
};
var diffIndexes = [];
var newTags = ['a','b','c'];
var oldTags = ['c'];
var diffValues = arrayDiff(newTags, oldTags);
console.log(diffIndexes); // [0, 1]
console.log(diffValues); // ['a', 'b']

【讨论】:

  • 不错的一个。我怎样才能将该效用函数转换为普通函数?
【解决方案2】:
for(var i=0; i < newTags.length; i++) {
    for(var j=0; j < oldTags.length; j++) {
        if(newTags[i] === oldTags[j]) {
            console.log("match found");
            console.log("Match found for value: " + newTags[i] + " at index in oldTags: " + j + );
         }
         else{
           console.log("match not found");
         }
    }
}

使用 2 个循环,您可以快速检查,在 if 语句中添加您想要发生的事情。

【讨论】:

    【解决方案3】:

    您不需要遍历两个数组,您可以简单地同时遍历两个数组:

    var findDivergence = function (a1, a2) {
        var result = [], longerLength = a1.length >= a2.length ? a1.length : a2.length;
        for (i = 0; i < longerLength; i++){
            if (a1[i] !== a2[i]) {
                result.push(i);
            }
        }
        return result;
    };
    
    console.log(findDivergence(["a","b","c","d","e","f","g","h","i"], ["a","b","d","r","e","q","g"]));
    //outputs [2, 3, 5, 7, 8]
    

    这比双循环或使用 indexOf 效率高得多(两者都将搜索第二个数组的次数超出必要的次数)。这也可以处理同一项目在给定数组中出现多次的情况,但如果一个数组比另一个数组长并且较长的一个包含未定义的元素,则该索引将被视为匹配项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      相关资源
      最近更新 更多