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

2022-01-25 00:00:00 arrays compare jquery javascript

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

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']

相关文章