Hi there I have 1 question regarding multiple array, I able to get matches arrays but how to get not matches arrays value?
var a = [1,2,3,4,5,6,7,8,9,10]
var b = [2,3,4,5,7,8,10]
for (var c = 0; c <a.length; a++ ){
for (var d = 0; d <b.length; d++ ){
if (a[c] == b[d]){
// array contain [2,3,4,5,7,8,10]
}
}
}
For the code to know that it’s unmatched, it needs to remember if it’s found the value anywhere throughout the array.
We can work our way forward to that by first starting off with a found variable, and use that found variable to log the values that are found:
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var b = [2, 3, 4, 5, 7, 8, 10]
var found;
for (var c = 0; c < a.length; c++) {
found = false;
for (var d = 0; d < b.length; d++) {
if (a[c] == b[d]) {
found = true;
}
}
if (found) {
console.log(a[c]); // 2, 3, 4, 5, 7, 8, 10
}
}
Now to get the values are are not found, we just need to invert the found condition from (found) to (!found)
Normally ES6 Sets are easier to work with for unions, intersections, and differences.
However, you can convert arrays so that you can work with them as sets. Here are some basic functions that perform union, intersection, and difference.
function arrayUnion(arr1, arr2) {
const a = new Set(arr1);
const b = new Set(arr2);
const union = new Set([...a, ...b]);
return Array.from(union);
}
function arrayIntersection(arr1, arr2) {
const a = new Set(arr1);
const b = new Set(arr2);
const intersection = new Set(
[...a].filter(x => b.has(x)));
return Array.from(intersection);
}
function arrayDifference(arr1, arr2) {
const a = new Set(arr1);
const b = new Set(arr2);
const difference = new Set(
[...a].filter(x => !b.has(x)));
return Array.from(difference);
}
And as the Set is only wanted for an easy Union, we can simplify those methods to just be:
function arrayUnion(a, b) {
return Array.from(new Set([...a, ...b]));
}
function arrayIntersection(a, b) {
return a.filter(x => b.includes(x));
}
function arrayDifference(a, b) {
return a.filter(x => !b.includes(x));
}
var a = [1,2,3,4,5,6,7,8,9,10];
var b = [2,3,4,5,7,8,10];
var unmatched = getUnmatchedArray(a, b);
function getUnmatchedArray(a, b){
var out = [];
for(var i=0; i<a.length; i++){
if(b.indexOf(a[i]) == -1){
out.push(a[i]);
}
}
return out;
}