Get values that are not present in another array in JavaScript

We are given two arrays: (arr1 and arr2) ?

  • arr1 contains some literal values.

  • arr2 contains objects that map some literal values.

We are required to write a JavaScript function that takes in two such arrays. Then the function should return an array of all the elements from arr1 that are not mapped by objects in arr2.

Example

The code for this will be ?

const arr1 = [111, 222, 333, 444];
const arr2 = [
   { identifier: 111 },
   { identifier: 222 },
   { identifier: 444 },
];

const getAbsentValues = (arr1, arr2) => {
   let res = [];
   res = arr1.filter(el => {
      return !arr2.find(obj => {
         return el === obj.identifier;
      });
   });
   return res;
};

console.log(getAbsentValues(arr1, arr2));
[ 333 ]

How It Works

The function uses the filter() method to iterate through arr1. For each element, it uses find() to check if that element exists as an identifier property in any object within arr2. The ! operator negates the result, so only elements that are NOT found in arr2 are included in the final array.

Alternative Approach Using Set

For better performance with larger arrays, you can use a Set:

const arr1 = [111, 222, 333, 444, 555];
const arr2 = [
   { identifier: 111 },
   { identifier: 222 },
   { identifier: 444 },
];

const getAbsentValuesOptimized = (arr1, arr2) => {
   const identifierSet = new Set(arr2.map(obj => obj.identifier));
   return arr1.filter(el => !identifierSet.has(el));
};

console.log(getAbsentValuesOptimized(arr1, arr2));
[ 333, 555 ]

Comparison

Method Time Complexity Best For
filter() + find() O(n × m) Small arrays
filter() + Set O(n + m) Large arrays

Conclusion

Use filter() with find() for simple cases, but consider the Set approach for better performance with larger datasets. Both methods effectively identify values present in one array but absent in another.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements