我有两个数组,我需要检查差异并返回该差异的索引。
例如,我目前有两个数组在输入值改变时得到更新。只要输入中有新标记,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;
}
});
答案 0 :(得分:2)
您可以使用过滤器同时查找不同的值和索引。
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']
答案 1 :(得分:1)
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语句中添加你想要发生的事情。
答案 2 :(得分:0)
您不需要遍历两个阵列,您可以简单地同时遍历两个阵列:
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更有效(两者都将搜索第二个数组的次数超过必要的次数)。这也处理同一项在给定数组中出现多次的情况,但如果一个数组比另一个数组长,而较长的数组包含未定义的元素,则该索引将计为匹配。