Compare 2 Arrays Which Returns Difference

How to get the difference between two arrays in JavaScript?

This answer was written in 2009, so it is a bit outdated, also it's rather educational for understanding the problem. Best solution I'd use today would be

let difference = arr1.filter(x => !arr2.includes(x));

(credits to other author here)

I assume you are comparing a normal array. If not, you need to change the for loop to a for .. in loop.

function arr_diff (a1, a2) {

var a = [], diff = [];

for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}

for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}

for (var k in a) {
diff.push(k);
}

return diff;
}

console.log(arr_diff(['a', 'b'], ['a', 'b', 'c', 'd']));
console.log(arr_diff("abcd", "abcde"));
console.log(arr_diff("zxc", "zxc"));

Compare 2 arrays which returns difference

Working demo http://jsfiddle.net/u9xES/

Good link (Jquery Documentation): http://docs.jquery.com/Main_Page {you can search or read APIs here}

Hope this will help you if you are looking to do it in JQuery.

The alert in the end prompts the array of uncommon element Array i.e. difference between 2 array.

Please lemme know if I missed anything, cheers!

Code

var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var difference = [];

jQuery.grep(array2, function(el) {
if (jQuery.inArray(el, array1) == -1) difference.push(el);
});

alert(" the difference is " + difference);​ // Changed variable name

How to get the difference between two arrays of objects in JavaScript

Using only native JS, something like this will work:

const a = [{ value:"0", display:"Jamsheer" }, { value:"1", display:"Muhammed" }, { value:"2", display:"Ravi" }, { value:"3", display:"Ajmal" }, { value:"4", display:"Ryan" }];
const b = [{ value:"0", display:"Jamsheer", $$hashKey:"008" }, { value:"1", display:"Muhammed", $$hashKey:"009" }, { value:"2", display:"Ravi", $$hashKey:"00A" }, { value:"3", display:"Ajmal", $$hashKey:"00B" }];

// A comparer used to determine if two entries are equal.
const isSameUser = (a, b) => a.value === b.value && a.display === b.display;

// Get items that only occur in the left array,
// using the compareFunction to determine equality.
const onlyInLeft = (left, right, compareFunction) =>
left.filter(leftValue =>
!right.some(rightValue =>
compareFunction(leftValue, rightValue)));

const onlyInA = onlyInLeft(a, b, isSameUser);
const onlyInB = onlyInLeft(b, a, isSameUser);

const result = [...onlyInA, ...onlyInB];

console.log(result);

How to compare two arrays and return a difference in JavaScript

Why don't you just filter the unwanted id?

const a = [8, 10, 13, 14];const b = [{ id: 8 }, { id: 13 }, { id: 14 }];
console.log(a.filter(num => !b.some(({ id }) => id === num)));

Comparing 2 arrays for differences (find symmetric difference)

The fastest solution in terms of time complexity is to create a Set or a hash from one array -> O(N), then iterate through the other to compare if an element is not the set -> O(M) -> and then add it to the diffs array.
The main benefit here is that Set lookup time is constant.
This solution also has space complexity of O(N) for building the set.

You can repeat this for the other array as well, giving you total of O(N) + O(M) + O(N) + O(M) which, when constant factors are removed, is just O(N+M) time complexity.

Building the set for the second array gives total space complexity as O(N+M).

// Total complexity// Time:  O(N+M)// Space: O(N+M)
// time complexities for each step shown bellow
let N = [1,2,3,6]let M = [2,3,4,5,7]
const setForN = new Set(N); // O(N)const setForM = new Set(M); // O(M)
// O(N + M) at this point
const answerN = N.filter(n => !setForM.has(n)) // O(N)const answerM = M.filter(m => !setForN.has(m)) // O(M)
// O(N + M) + O(N + M) at this point, which is just O(N + M)
console.log(answerN, answerM);

How to compare two arrays and return the difference? (Working both ways?)

To find the values that appear in one but not the other use lodash's

_.xor(array1, array2);

In your case:

> const _ = require('lodash');

> const old = [
... { id: 1, name: 'object_1' },
... { id: 2, name: 'object_2' },
... { id: 3, name: 'object_3' },
... { id: 4, name: 'object_4' },
... ];

> const newIds = [1, 3, 5, 7];

> _.xor(old.map(x => x.id), newIds)
[ 2, 4, 5, 7 ]

How can I find matching values in two arrays?

Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is > -1, then push it onto the returned array.

​Array.prototype.diff = function(arr2) {
var ret = [];
for(var i in this) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};


My solution doesn't use two loops like others do so it may run a bit faster. If you want to avoid using for..in, you can sort both arrays first to reindex all their values:

Array.prototype.diff = function(arr2) {
var ret = [];
this.sort();
arr2.sort();
for(var i = 0; i < this.length; i += 1) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};

Usage would look like:

var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];

console.log(array1.diff(array2));

If you have an issue/problem with extending the Array prototype, you could easily change this to a function.

var diff = function(arr, arr2) {

And you'd change anywhere where the func originally said this to arr2.

Javascript -- Compare two arrays, return differences, BUT

Just iterate over the array of elements you want to remove.

var array1 = ['A', 'B', 'C', 'D', 'D', 'E'];
var array2 = ['D', 'E'];
var index;

for (var i=0; i<array2.length; i++) {
index = array1.indexOf(array2[i]);
if (index > -1) {
array1.splice(index, 1);
}
}

It's O(array1.length * array2.length) but for reasonably small arrays and on modern hardware this shouldn't remotely cause an issue.

http://jsfiddle.net/mattball/puz7q/

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice

Lodash / javascript : Compare two collections and return the differences

var presents = _.intersectionWith(array1, array2, _.isEqual);
var dif = _.differenceWith(array1, array2, _.isEqual);

_.differenceWith is only available since 4.0.0 lodash version



Related Topics



Leave a reply



Submit