I got two arrays, so I want to display values of array1 that are missing or extra compared to array2.
For example :
var array1 = [1,1,2,3,5,6]; var array2 = [0,1,2,4];
Result : ==> Missing : 0,1,4 ==> Extra : 3,5,6
I got two arrays, so I want to display values of array1 that are missing or extra compared to array2.
For example :
var array1 = [1,1,2,3,5,6]; var array2 = [0,1,2,4];
Result : ==> Missing : 0,1,4 ==> Extra : 3,5,6
For a really dumb implementation, you can just check it yourself:
var array1 = [1, 2, 3, 5, 6];
var array2 = [0, 1, 2, 4];
var missing = [];
var extra = [];
for(var i = 0; i < Math.max(array1.length, array2.length); i++) {
if (i < array1.length && array2.indexOf(array1[i]) === -1) {
extra.push(array1[i]);
}
if (i < array2.length && array1.indexOf(array2[i]) === -1) {
missing.push(array2[i]);
}
}
console.log('Result: ==> Missing: ' + missing + ' Extra: ' + extra);
Or, if you can use filter:
var array1 = [1, 2, 3, 5, 6];
var array2 = [0, 1, 2, 4];
var extra = array1.filter(function(item) { return array2.indexOf(item) === -1 });
var missing = array2.filter(function(item) { return array1.indexOf(item) === -1 });
console.log('Result: ==> Missing: ' + missing + ' Extra: ' + extra);
function comparator(a, b) { return a - b }
function compare(ar1, ar2) {
ar1 = ar1.slice().sort(comparator)
ar2 = ar2.slice().sort(comparator)
let missing = []
let extra = []
let pos1 = 0
let pos2 = 0
while(pos1 < ar1.length && pos2 < ar2.length) {
const item1 = ar1[pos1]
const item2 = ar2[pos2]
if (item1 === item2) {
pos1++
pos2++
} else if (item1 < item2) {
extra.push(item1)
pos1++
} else {
missing.push(item2)
pos2++
}
}
extra = extra.concat(ar1.slice(pos1))
missing = missing.concat(ar2.slice(pos2))
return {
missing,
extra
}
}
console.log(compare([1,1,2,3,5,6], [0,1,2,4]))