简体   繁体   中英

How to get all items that are both is array A and B and save them in array C? using javascript without using loops

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM