Use a combination of Array.prototype.filter and Array.prototype.includes:

const filteredArray = array1.filter(value => array2.includes(value));

For older browsers, with Array.prototype.indexOf and without an arrow function:

var filteredArray = array1.filter(function(n) {
    return array2.indexOf(n) !== -1;
});

NB! Both .includes and .indexOf internally compares elements in the array by using ===, so if the array contains objects it will only compare object references (not their content). If you want to specify your own comparison logic, use Array.prototype.some instead.

Answer from Anon. on Stack Overflow
Top answer
1 of 16
1960

Use a combination of Array.prototype.filter and Array.prototype.includes:

const filteredArray = array1.filter(value => array2.includes(value));

For older browsers, with Array.prototype.indexOf and without an arrow function:

var filteredArray = array1.filter(function(n) {
    return array2.indexOf(n) !== -1;
});

NB! Both .includes and .indexOf internally compares elements in the array by using ===, so if the array contains objects it will only compare object references (not their content). If you want to specify your own comparison logic, use Array.prototype.some instead.

2 of 16
163

Destructive seems simplest, especially if we can assume the input is sorted:

/* destructively finds the intersection of 
 * two arrays in a simple fashion.  
 *
 * PARAMS
 *  a - first array, must already be sorted
 *  b - second array, must already be sorted
 *
 * NOTES
 *  State of input arrays is undefined when
 *  the function returns.  They should be 
 *  (prolly) be dumped.
 *
 *  Should have O(n) operations, where n is 
 *    n = MIN(a.length, b.length)
 */
function intersection_destructive(a, b)
{
  var result = [];
  while( a.length > 0 && b.length > 0 )
  {  
     if      (a[0] < b[0] ){ a.shift(); }
     else if (a[0] > b[0] ){ b.shift(); }
     else /* they're equal */
     {
       result.push(a.shift());
       b.shift();
     }
  }

  return result;
}

Non-destructive has to be a hair more complicated, since we’ve got to track indices:

/* finds the intersection of 
 * two arrays in a simple fashion.  
 *
 * PARAMS
 *  a - first array, must already be sorted
 *  b - second array, must already be sorted
 *
 * NOTES
 *
 *  Should have O(n) operations, where n is 
 *    n = MIN(a.length(), b.length())
 */
function intersect_safe(a, b)
{
  var ai=0, bi=0;
  var result = [];

  while( ai < a.length && bi < b.length )
  {
     if      (a[ai] < b[bi] ){ ai++; }
     else if (a[ai] > b[bi] ){ bi++; }
     else /* they're equal */
     {
       result.push(a[ai]);
       ai++;
       bi++;
     }
  }

  return result;
}
🌐
Medium
medium.com › @alvaro.saburido › set-theory-for-arrays-in-es6-eb2f20a61848
Array intersection, difference, and union in ES6 | by Alvaro Saburido | Medium
August 2, 2020 - Hi everyone, today I bring you some ES6 magic for common Array algorithms that sometimes, we overthink, and they have a really easy one-lined solution using high order functions like filter and Set theory. What in the world is Set theory? Just a branch of mathematical logic that studies sets, which informally are collections of objects. We are not covering the same methods for Javascript ...
Discussions

How to calculate the intersection of multiple arrays in JavaScript
You skip over the interesting part of object comparisons (comparing the objects) entirely by going for a "key" property (without explaining why), and go directly to code (with, I think, at least one bug) instead of explaining concepts. I think this would be a better and more useful read if you included more background, theory, and practical comparisons (beyond just the order of elements). More on reddit.com
🌐 r/javascript
12
23
March 15, 2023
javascript - Array of objects intersection - Stack Overflow
This returns exactly the array1 whereas if I replace != with == it returns the objects I want to get rid of. More on stackoverflow.com
🌐 stackoverflow.com
javascript - Difference and intersection of two arrays containing objects - Stack Overflow
0 How to get the intersection and symmetric difference of 2 objects in seperate arrays with Javascript More on stackoverflow.com
🌐 stackoverflow.com
How to extract proper intersection type from an array?
the module that gives me this collection has return type of A[] & B[] I'm assuming this is an npm module that's used a lot in the code base named "library-that-is-typed-wrong": A) Go to github.com/library-that-is-typed-wrong and submit an issue that the types are wrong, feel free to link this thread if you don't feel confident defending it. (note: might be in the DefinitelyTyped github) B) In your project src/ create a @types/library-that-is-typed-wrong.d.ts file C) Add: declare module 'library-that-is-typed-wrong' { export const theOneMethodThatIsMessingYouUp: () => (A & B)[]; } D) Your util functions should now play nice Other options include force casting the return type of the method const collection = theOneMethodThatIsMessingYouUp() (okay if it's used in one or two places), or creating a wrapper module that abstracts away the library internal and fixing the types on your things (this is good practice anyways if it's a core module that's used everywhere) More on reddit.com
🌐 r/typescript
17
10
March 16, 2021
🌐
GitHub
github.com › lovasoa › fast_array_intersect
GitHub - lovasoa/fast_array_intersect: The fastest javascript array intersection function · GitHub
By default, the intersection is computed for values that are equal under SameValueZero. You can use the optional hash function argument when you are intersecting arrays of javascript objects.
Author: lovasoa
🌐
4Geeks
4geeks.com › en › how-to › javascript-array-intersection
JavaScript Array Intersection: filter(), Loops and Set
2 weeks ago - Find the intersection of two arrays in JavaScript with filter() and includes(), a for loop or a Set, plus a real-world example you can copy.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Set › intersection
Set.prototype.intersection() - JavaScript - MDN Web Docs
May 22, 2026 - The intersection() method of Set instances takes a set and returns a new set containing elements in both this set and the given set.
🌐
Reddit
reddit.com › r/javascript › how to calculate the intersection of multiple arrays in javascript
r/javascript on Reddit: How to calculate the intersection of multiple arrays in JavaScript
March 15, 2023 - Intersecting Set is linear and only grows with your smallest set. This solution appears to be linear but you have to iterate over every value in all compared arrays.
Find elsewhere
🌐
GitHub
gist.github.com › lovasoa › 3361645
Compute the intersection of large arrays in javascript · GitHub
The idea is simple and comes from here: http://pioupioum.fr/developpement/javascript-array-intersection.html. To make short story even shorter: It creates a javascript object, the keys of which are the elements of the smallest of the arrays we want to intersect.
🌐
Programiz
programiz.com › javascript › examples › intersection-two-arrays
JavaScript Program To Perform Intersection Between Two Arrays
To understand this example, you should have the knowledge of the following JavaScript programming topics: ... // program to perform intersection between two arrays using Set // intersection contains the elements of array1 that are also in array2 function performIntersection(arr1, arr2) { // converting into Set const setA = new Set(arr1); const setB = new Set(arr2); let intersectionResult = []; for (let i of setB) { if (setA.has(i)) { intersectionResult.push(i); } } return intersectionResult; } const array1 = [1, 2, 3, 5, 9]; const array2 = [1, 3, 5, 8]; const result = performIntersection(array1, array2); console.log(result);
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-get-intersection-of-two-arrays
Get the Intersection of two Arrays or Sets in JavaScript | bobbyhadz
The Array.reduce() method returns ... use the lodash library. Install the lodash library. ... Use the intersection() method to get the intersection of two or more arrays....
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-program-to-find-intersection-of-unsorted-arrays
JavaScript Program to find Intersection of Unsorted Arrays - GeeksforGeeks
July 23, 2025 - Below are the approaches to Find the Intersection of Unsorted Arrays in JavaScript: ... The filter() method creates a new array by filtering elements based on a provided condition.
Top answer
1 of 8
60

You could define three functions inBoth, inFirstOnly, and inSecondOnly which all take two lists as arguments, and return a list as can be understood from the function name. The main logic could be put in a common function operation that all three rely on.

Here are a few implementations for that operation to choose from, for which you can find a snippet further down:

  • Plain old JavaScript for loops
  • Arrow functions using filter and some array methods
  • Optimised lookup with a Set

Plain old for loops

// Generic helper function that can be used for the three operations:        
function operation(list1, list2, isUnion) {
    var result = [];
    
    for (var i = 0; i < list1.length; i++) {
        var item1 = list1[i],
            found = false;
        for (var j = 0; j < list2.length && !found; j++) {
            found = item1.userId === list2[j].userId;
        }
        if (found === !!isUnion) { // isUnion is coerced to boolean
            result.push(item1);
        }
    }
    return result;
}

// Following functions are to be used:
function inBoth(list1, list2) {
    return operation(list1, list2, true);
}

function inFirstOnly(list1, list2) {
    return operation(list1, list2);
}

function inSecondOnly(list1, list2) {
    return inFirstOnly(list2, list1);
}

// Sample data
var list1 = [
    { userId: 1234, userName: 'XYZ'  }, 
    { userId: 1235, userName: 'ABC'  }, 
    { userId: 1236, userName: 'IJKL' },
    { userId: 1237, userName: 'WXYZ' }, 
    { userId: 1238, userName: 'LMNO' }
];
var list2 = [
    { userId: 1235, userName: 'ABC'  },  
    { userId: 1236, userName: 'IJKL' },
    { userId: 1252, userName: 'AAAA' }
];
  
console.log('inBoth:', inBoth(list1, list2)); 
console.log('inFirstOnly:', inFirstOnly(list1, list2)); 
console.log('inSecondOnly:', inSecondOnly(list1, list2)); 
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Arrow functions using filter and some array methods

This uses some ES5 and ES6 features:

// Generic helper function that can be used for the three operations:        
const operation = (list1, list2, isUnion = false) =>
    list1.filter( a => isUnion === list2.some( b => a.userId === b.userId ) );

// Following functions are to be used:
const inBoth = (list1, list2) => operation(list1, list2, true),
      inFirstOnly = operation,
      inSecondOnly = (list1, list2) => inFirstOnly(list2, list1);

// Sample data
const list1 = [
    { userId: 1234, userName: 'XYZ'  }, 
    { userId: 1235, userName: 'ABC'  }, 
    { userId: 1236, userName: 'IJKL' },
    { userId: 1237, userName: 'WXYZ' }, 
    { userId: 1238, userName: 'LMNO' }
];
const list2 = [
    { userId: 1235, userName: 'ABC'  },  
    { userId: 1236, userName: 'IJKL' },
    { userId: 1252, userName: 'AAAA' }
];
  
console.log('inBoth:', inBoth(list1, list2)); 
console.log('inFirstOnly:', inFirstOnly(list1, list2)); 
console.log('inSecondOnly:', inSecondOnly(list1, list2));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Optimising lookup

The above solutions have a O(n²) time complexity because of the nested loop -- some represents a loop as well. So for large arrays you'd better create a (temporary) hash on user-id. This can be done on-the-fly by providing a Set (ES6) as argument to a function that will generate the filter callback function. That function can then perform the look-up in constant time with has:

// Generic helper function that can be used for the three operations:        
const operation = (list1, list2, isUnion = false) =>
    list1.filter(
        (set => a => isUnion === set.has(a.userId))(new Set(list2.map(b => b.userId)))
    );

// Following functions are to be used:
const inBoth = (list1, list2) => operation(list1, list2, true),
      inFirstOnly = operation,
      inSecondOnly = (list1, list2) => inFirstOnly(list2, list1);

// Sample data
const list1 = [
    { userId: 1234, userName: 'XYZ'  }, 
    { userId: 1235, userName: 'ABC'  }, 
    { userId: 1236, userName: 'IJKL' },
    { userId: 1237, userName: 'WXYZ' }, 
    { userId: 1238, userName: 'LMNO' }
];
const list2 = [
    { userId: 1235, userName: 'ABC'  },  
    { userId: 1236, userName: 'IJKL' },
    { userId: 1252, userName: 'AAAA' }
];
  
console.log('inBoth:', inBoth(list1, list2)); 
console.log('inFirstOnly:', inFirstOnly(list1, list2)); 
console.log('inSecondOnly:', inSecondOnly(list1, list2));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 8
43

short answer:

list1.filter(a => list2.some(b => a.userId === b.userId));  
list1.filter(a => !list2.some(b => a.userId === b.userId));  
list2.filter(a => !list1.some(b => a.userId === b.userId));  

longer answer:
The code above will check objects by userId value,
if you need complex compare rules, you can define custom comparator:

comparator = function (a, b) {
    return a.userId === b.userId && a.userName === b.userName
};  
list1.filter(a => list2.some(b => comparator(a, b)));
list1.filter(a => !list2.some(b => comparator(a, b)));
list2.filter(a => !list1.some(b => comparator(a, b)));

Also there is a way to compare objects by references
WARNING! two objects with same values will be considered different:

o1 = {"userId":1};
o2 = {"userId":2};
o1_copy = {"userId":1};
o1_ref = o1;
[o1].filter(a => [o2].includes(a)).length; // 0
[o1].filter(a => [o1_copy].includes(a)).length; // 0
[o1].filter(a => [o1_ref].includes(a)).length; // 1
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-create-an-array-using-intersection-of-two-arrays-in-javascript
How to Create an Array using Intersection of two Arrays in JavaScript ? | GeeksforGeeks
Using the reduce method, iterate through one array, adding elements that are present in both arrays to a new array. Check for element inclusion in the second array using the includes method, effectively creating an array representing their ...
Published: May 21, 2024
🌐
Vultr Docs
docs.vultr.com › javascript › examples › perform-intersection-between-two-arrays
JavaScript Program to Perform Intersection Between Two Arrays | Vultr Docs
December 18, 2024 - This code snippet creates two arrays and filters array1 to include only the elements that are also present in array2, resulting in an intersection of [4, 5]. The filter() method iterates through each item of array1, and the includes() method checks if that item exists in array2.
🌐
Medium
medium.com › @stheodorejohn › finding-the-intersection-of-two-arrays-in-javascript-8bd54c5c9c08
Finding the Intersection of Two Arrays in JavaScript | by Theodore John.S | Medium
June 23, 2023 - Approach 1: Using Built-in Functions We can utilize JavaScript’s built-in functions to solve this problem efficiently. The filter function can be used to iterate over one array and return the elements that exist in the second array.
🌐
JavaScript in Plain English
javascript.plainenglish.io › typescript-intersection-best-practice-6a7de85bb2f1
TypeScript Intersection Best Practices | by Dexter Chang | JavaScript in Plain English
March 18, 2021 - Note: Array.find() is also a O(n) function, but the advantage is that once it find a elements match the requested value, it will jump out of the loop. So, after 3 ways to implement a function to retrieve intersection, you might notice that the mininum for-loop is 2, so you would have lots of ways to do this, for example:
🌐
Techie Delight
techiedelight.com › home › java › find intersection of two arrays in javascript
Find intersection of two arrays in JavaScript | Techie Delight
July 7, 2026 - Another solution is to convert the array into an ES6 Set and call its has() method to check for the other array elements.
🌐
Go Make Things
gomakethings.com › articles › how-to-find-the-intersecting-values-of-two-arrays-with-vanilla-javascript
How to find the intersecting values of two arrays with vanilla JavaScript | Go Make Things
/** * Get the intersecting values between two arrays * @param {Array} arr1 The first array * @param {Array} arr2 The second array * @return {Array} The array of overlapping values */ function arrayIntersect (arr1, arr2) { return arr1.filter(function ...
🌐
LabEx
labex.io › tutorials › javascript-check-if-two-arrays-intersect-28165
Array Intersection | JavaScript Algorithms | LabEx
Use Array.prototype.some() on a to check if any of its values are contained in b, using Set.prototype.has(). Use the intersects function provided below to test the arrays.