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']
这篇关于如何比较两个数组,然后返回差异的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何比较两个数组,然后返回差异的索引?
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01