Get values that are not present in another array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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

Output

The output in the console −

[ 333 ]
raja
Published on 10-Oct-2020 08:15:43
Advertisements