0

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

Kamga Simo Junior
  • 1,679
  • 2
  • 16
  • 30

4 Answers4

2

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);
guest271314
  • 1
  • 15
  • 104
  • 177
1

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"]
warch
  • 2,387
  • 2
  • 26
  • 43
  • what will be the value of C – Kamga Simo Junior Jul 20 '17 at 04:10
  • in the first example: `["x", "y", "z", 1, 2, "z", 3, "x"]` and in the second one `["x", "y", "z", 1, 2, 3]` – warch Jul 20 '17 at 04:11
  • i want C to be `[x, z]` the intersect – Kamga Simo Junior Jul 20 '17 at 04:13
  • a.indexOf is still a linear search -> you're just calling a convenience method for a loop that loops through the entire array until it finds a match or it's looped through every item in the array without a match. – Xingzhou Liu Jul 20 '17 at 04:13
  • 1
    then you should use ```A.filter(function(n) { return B.indexOf(n) !== -1; });``` – warch Jul 20 '17 at 04:16
  • You are still looping! for every item in a, you are looping through either every element in B (for indexOf = -1) or until you find a match in B. calling indexOf === doing a loop. You still loop through B multiple times. – Xingzhou Liu Jul 20 '17 at 04:19
1

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);
H77
  • 5,859
  • 2
  • 26
  • 39
-2

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).

Xingzhou Liu
  • 1,507
  • 8
  • 12