如何比较两个数组,然后返回差异的索引?

How to compare two arrays and then return the index of the difference?(如何比较两个数组,然后返回差异的索引?)

本文介绍了如何比较两个数组,然后返回差异的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two arrays that I need to check the difference upon and return the index of that difference.

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

For example, I currently have two arrays that get updated when the input's value is changed. The newTags array gets updated whenever there is a new tag within the input, such as @testing. I need to compare the newTags array with the oldTags array and return the index of the difference.

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

I am currently stringifying both arrays and comparing them that way, although it is unable to return the index of the difference.

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;
    }
});

工作示例

推荐答案

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

You can use a filter to find both the different values and indexes at the same time.

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/

To convert this to a function instead of add it to the array prototype: 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']

这篇关于如何比较两个数组,然后返回差异的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何比较两个数组,然后返回差异的索引?