lets say I have
var A = [x, y, z]
var B = [1, 2, z, 3, x]
How can I get items present both in A and B like so
var C = [AB]
Without having to loop through both arrays to check for each iteration
lets say I have
var A = [x, y, z]
var B = [1, 2, z, 3, x]
How can I get items present both in A and B like so
var C = [AB]
Without having to loop through both arrays to check for each iteration
You can use Array.prototype.filter()
and Array.prototype.includes()
to determine if both arrays contain the same element, Set
to remove duplicate elements from resulting array
var A = ["x", "y", "z"]
var B = [1, 2, "z", 3, "x"]
var C = [...new Set(
[...A, ...B].filter(prop => A.includes(prop) && B.includes(prop)))
];
console.log(C);
With duplicates:
var C = [...A, ...B]
// Result: C = ["x", "y", "z", 1, 2, "z", 3, "x"]
Without duplicates:
var C = [...A, ...B].filter((el, i, a) => i === a.indexOf(el))
// Result: C = ["x", "y", "z", 1, 2, 3]
Update: if you want the intersection of both arrays:
var C = A.filter(function(n) {
return B.indexOf(n) !== -1;
});
// Result: C = ["x", "z"]
let a = new Set(["x", "y", "z"]);
let b = new Set([1, 2, "z", 3, "x"]);
let intersection = [...a].filter(x => b.has(x));
console.log(intersection);
Sort each array then merge?
/* sort DESC */
A.sort(function(a,b){ return b-a; })
B.sort(function(a,b){ return b-a; })
then use:
function union_destructive(a, b)
{
var result = [];
while( a.length > 0 || b.length > 0 )
{
if (a[0] > b[0] ){ result.push(a.shift()); }
else if (a[0] < b[0] ){ result.push(b.shift()); }
else /* they're equal */
{
result.push(a.shift());
b.shift();
}
}
return result;
}
(Simplest code for array intersection in javascript):
Thats O(n log n).