Skip to content
the poor coder

javascript select from one array do not exist in another array

Poor Man
Published
Reading time
2 min read

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:

Text
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:

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

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC