I have 2 arrays as follows. I want to compare both arrays and only provide the elements from 'check' which are not present in 'data' array.
var check= ["044", "451"],
data = ["343", "333", "044", "123", "444", "555"];
The function used is as follows. This function will result in providing the elements in 'check' array which are present in 'data' array
function getMatch(a, b) {
var matches = [];
for ( var i = 0; i < a.length; i++ ) {
for ( var e = 0; e < b.length; e++ ) {
if ( a[i] === b[e] ) matches.push( a[i] );
}
}
return matches;
}
getMatch(check, data); // ["044"] ---> this will be the answer as '044' is only present in 'data'
I want to have a list of elements which are not present in 'data' array. Can someone let me know how to achieve this.
You could use filter
and Set
, providing the Set
as context to the filter
method, so it can be accessed as this
:
var check= ["044", "451"],
data = ["343", "333", "044", "123", "444", "555"];
var res = check.filter( function(n) { return !this.has(n) }, new Set(data) );
console.log(res);
Note that this runs in O(n) time, contrary to indexOf
/includes
based solutions, which really represent a nested loop.
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