Reputation: 441
I have a two array with with different values. I'd like to match the arrays and spearate the values that is not match. It's my current script:
var array_must_exist = ['4','5'];
var array_to_compare = [{"NO": "1"},{"NO": "2"},{"NO": "5"},{"NO": "7"}];
$.each(array_to_compare, function(i, result){
var arr = jQuery.grep(array_must_exist, function(value) {
return value != result.NO;
});
alert(arr);
});
When array_must_exist
is in array_to_compare
the arr
returns 5
and 4
. How to alert the one is not in the array?
if array_to_compare = [{"NO": "1"},{"NO": "4"}];
the alert is 5 is missing
if array_to_compare = [{"NO": "5"},{"NO": "6"},{"NO": "3"}];
the alert is 4 is missing
if array_to_compare = [{"NO": "4"},{"NO": "5"},{"NO": "6"},{"NO": "7"}];
the alert is Nothing is missing
Upvotes: 0
Views: 50
Reputation:
You just need to .filter()
the array_must_exist
array down to ones where .some()
is not able to locate a match in array_to_compare
.
var array_must_exist = ['4','5'];
var array_to_compare = [{"NO": "1"},{"NO": "2"},{"NO": "5"},{"NO": "7"}];
var missing = array_must_exist.filter(n => // `n` is the current number.
!array_to_compare.some(obj => obj.NO == n) // See if `n` is in any object.
);
console.log("missing:", missing.length ? missing : "None")
So for each item in array_must_exist
, if "not some" (or in other words "none") are found in array_to_compare
, that value will be included in the result. If the result is empty, then all were found.
Upvotes: 2
Reputation: 33726
You can use the functions reduce
and findIndex
to extract the missing values.
function compare(array_must_exist, array_to_compare) {
return array_must_exist.reduce((a, c) => {
if (array_to_compare.findIndex((a) => a.NO === c) === -1) a.push(c);
return a;
}, []);
}
console.log('Missing:', compare(['4','5'], [{"NO": "1"},{"NO": "2"},{"NO": "5"},{"NO": "7"}]).join());
console.log('Missing:', compare(['4','5'], [{"NO": "4"}]).join());
console.log('Missing:', compare(['4','5'], [{"NO": "4"}, {"NO": "5"}]).join());
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1