javascript select from one array do not exist in another array

How to select values from one array that do not exist in another array using JavaScript

If you have two arrays and you want to select values from one array that do not exist in another array, you can use the filter() method to accomplish this. Here is how you can do it:

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];

const result = arr1.filter(value => !arr2.includes(value));

console.log(result); // Output: [1, 2]

In the code above, we created two arrays arr1 and arr2. Then we used the filter() method on arr1 to select only those values that do not exist in arr2. The !arr2.includes(value) condition checks whether the value exists in arr2 and negates the result to return only those values that do not exist in arr2.

Another way to do it using Set

You can also use the Set object to accomplish the same thing. Here is how:

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];

const set1 = new Set(arr1);
const set2 = new Set(arr2);

const result = Array.from(set1).filter(value => !set2.has(value));

console.log(result); // Output: [1, 2]

In the code above, we created two sets set1 and set2 from the arrays arr1 and arr2 respectively. Then we used the filter() method on set1 to select only those values that do not exist in set2. The !set2.has(value) condition checks whether the value exists in set2 and negates the result to return only those values that do not exist in set2.

Using a Set object can be faster than using the includes() method for large arrays because the lookup time for a Set is constant time O(1) while the lookup time for the includes() method is linear time O(n).

In conclusion, you can use either the filter() method or the Set object to select values from one array that do not exist in another array in JavaScript.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe