Possible Duplicate:
What is the fastest or most elegant way to compute a set difference using Javascript arrays?
I need help with devising a function that will return the difference between two arrays of strings in Javascript (jQuery is acceptable as well).
I am basically looking for a function that calculates array A minus B.
So if we have the followin"
A = ['Istanbul', 'Hong Kong', 'Berlin']; B = ['Berlin', 'Bonn'];
Calling diff = minus(A,B)
should result with diff
being populated with the following values ['Istanbul', 'Hong Kong']
I do not want to use an additional library like JS Set
.
Please help with suggestions ...
To get the difference between two arrays: Use the filter() method to iterate over the first array. Check if each element is not contained in the second array. Repeat the steps, but this time iterate over the second array.
The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.
Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.
function diff(A, B) {
return A.filter(function (a) {
return B.indexOf(a) == -1;
});
}
The fastest would probably be a regular loop
var A = ['Istanbul', 'Hong Kong', 'Berlin'],
B = ['Berlin', 'Bonn'],
C = [];
for (var i=A.length; i--;) {
if (B.indexOf(A[i]) === -1)
C.push(A[i]);
}
console.log(C);
The most elegant is opinion-based, but something like
var A = ['Istanbul', 'Hong Kong', 'Berlin'],
B = ['Berlin', 'Bonn'];
var C = A.filter(x => !B.includes(x));
console.log(C);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With