Compare array of objects - JavaScript


We have two arrays of objects like these −

const blocks = [
   { id: 1 },
   { id: 2 },
   { id: 3 },
   { id: 4 },
]
const containers = [
   { block: { id: 1 } },
   { block: { id: 2 } },
   { block: { id: 3 } },
]

We are required to write a function that checks each object of blocks array with the block key of each object of containers array and see if there exists any id in blocks array that is not present in the containers array. If so, we return false, otherwise we return true.

Example

Let’s write the code −

const blocks = [
   { id: 1 },
   { id: 2 },
   { id: 3 },
   { id: 4 },
]
const containers = [
   { block: { id: 1 } },
   { block: { id: 2 } },
   { block: { id: 3 } },
]
const checkProperty = (first, second) => {
   const findInContainers = id => {
      for(let i = 0; i < second.length; i++){
         if(second[i].block.id === id){
            return true;
         };
      };
      return false;
   };
   for(let i = 0; i < first.length; i++){
      if(!findInContainers(first[i].id)){
         return false;
      };
   };
   return true;
};
console.log(checkProperty(blocks, containers));

Output

Following is the output in the console −

false

Updated on: 14-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements