Reputation: 673
Essentially i have 2 arrays.
the resulting unmatched
array has duplicates, it should drop item in the array once found, which will lead to the countB
variable being smaller once it is finished and no duplicates i the unmatched
array
const arr1 = ['Bill', 'Bob', 'John'];
const arr2 = ['Bill', 'Jane', 'John'];
const matched = [];
const unmatched = [];
countA = 0;
countB = 0;
/* Result expected
matched = [Bill, John]
unmatched = [Bob, Jane] */
arr1.forEach((e1) => {
countA++;
for (const e2 of arr2) {
countB++;
if (e1 == e2) {
matched.push(e1);
break;
} else {
unmatched.push(e2);
}
}
});
console.log("unmatched",unmatched);
console.log("matched", matched);
console.log(`Counts ForEach Loop A:${countA} For In Loop B:${countB}`);
The Result expected are two arrays:
matched = [Bill, John]
unmatched = [Bob, Jane]
Upvotes: 1
Views: 54
Reputation: 386660
You could take a Set
and check if the actual value of the second array is in the set or not. Take the array as required and push the element to it.
const
array1 = ['Bill', 'Bob', 'John'],
array2 = ['Bill', 'Jane', 'John'],
set1 = new Set(array1),
matched = [],
unmatched = [];
array2.forEach(v => (set1.delete(v) ? matched : unmatched).push(v));
unmatched.push(...set1);
console.log(matched);
console.log(unmatched);
Upvotes: 1
Reputation: 508
Use the Array.prototype.indexOf()
for that
for ( let i = 0; i = arr1.length; i++ ) {
if ( arr2.indexOf( arr1[i] ) > -1 )
matched.push( arr1[i] );
else
unmatched.push( arr[i] );
}
const arr1 = ['Bill', 'Bob', 'John'];
const arr2 = ['Bill', 'Jane', 'John'];
const matched = [];
const unmatched = [];
countA = 0;
countB = 0;
/* Result expected
matched = [Bill, John]
unmatched = [Jane] */
for (let i = 0; (i < arr1.length); i++) {
countA++;
if (arr2.indexOf(arr1[i]) > -1) matched.push(arr1[i] );
else unmatched.push(arr1[i]); countB++;
}
console.log('unmatched', unmatched);
console.log('matched', matched);
console.log(`Counts ForEach Loop A:${countA} For In Loop B:${countB}`);
Upvotes: 0