[英]javascript compare two array find difference
我有兩個數組,可以是整數數組,字符串數組甚至是對象數組,出於演示目的,我將使用整數數組。
array1: array2:
0 99
1 1
101 5
2 100
100 97
5 101
4 4
我想要一個函數返回數組,其中包含有關兩個數組之間差異的所有信息。 結果將是:
0 -- {match:false,leftIndex:0 }
-- 99 {match:false: rightIndex:0}
1 1 {match:true: leftIndex:1,rightIndex:1}
-- 5 {match:false: rightIndex:2}
-- 100 {match:false: rightIndex:3}
-- 97 {match:false: rightIndex:4}
101 101 {match:false:leftIndex:2,rightIndex:5}
2 -- {match:false:leftIndex:3 }
100 -- {match:false:leftIndex:4 }
5 -- {match:false:leftIndex:5 }
4 4 {match:false:leftIndex:6,rightIndex:6}
解決此問題的最佳方法是什么? 我計划使用此函數通過angularJS指令方法顯示這兩個數組的並排視圖。 那行得通嗎?
如果rightIndex
和leftIndex
小於零,建議將Map
用作鍵的值並將索引用作匹配檢查的值。
在這種情況下,找到了一個匹配的項目,如果右側缺少一些其他值,則會對其進行糾察。
對於最后一部分,也會推送array2
剩余數據。
0 1 2 4 5 97 99 100 101 values 0 1 3 6 5 - - 4 2 leftIndex - 1 - 6 2 4 0 3 5 rightIndex - 0 - 0 -3 - - -1 3 delta: p2 - p1 * * * relevant only delta >= 0
var array1 = [0, 1, 101, 2, 100, 5, 4], array2 = [ 99, 1, 5, 100, 97, 101, 4], map = new Map, j = 0, result = []; array2.forEach(map.set.bind(map)); array1.forEach(function (a, i) { if (map.has(a) && map.get(a) >= i) { while (j < map.get(a)) { result.push({ value: array2[j], match: false, rightIndex: j }); j++; } result.push({ value: a, match: true, leftIndex: i, rightIndex: j }); j++; return; } result.push({ value: a, match: false, leftIndex: i }); }); while (j < array2.length) { result.push({ value: array2[j], match: false, rightIndex: j }); j++; } console.log(result);
如果您可以使用ES6的最新功能,我將提供以下類似信息:
function areArrayEqual(array1, array2) {
// Based on http://stackoverflow.com/a/14853974/2586392
if (array1.length !== array2.length) return false;
for (var i = 0, l=array1.length; i < l; i++) {
if (!areArrayEqual(array1[i], array2[i]) return false;
else if (array1[i] != array2[i]) return false;
}
return true;
})
var result = [];
array1.forEach((value, i) => {
let j = array2.findIndex(x => {
if (typeof value !== typeof x) return false;
if (typeof value === 'object') return areArrayEquals(Object.values(x), Object.values(value));
if (typeof value === 'array') return areArrayEquals(x, value);
return x === value;
});
result.push([value, j === -1 ? '---' : value , {
match: !!(j + 1),
leftIndex: i,
rightIndex: j === -1 ? '---' : j
}]);
if (j !== -1) {
delete array2[j];
}
});
array2.forEach((value, i) => {
result.push(['---', value, {match: false, leftIndex: '---', rightIndex: i}]);
});
否則,您仍然可以使用類似的東西,但是您需要Object.values
以及forEach
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.