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.

Using Traditional Loop Method

Let's write the code using nested loops:

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 

false

The function returns false because block with id 4 exists in blocks array but not in containers array.

Using Array Methods (Modern Approach)

A more modern approach using every() and some() array methods:

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

const checkPropertyModern = (first, second) => {
   return first.every(block => 
      second.some(container => container.block.id === block.id)
   );
};

console.log(checkPropertyModern(blocks, containers));
false

Testing with Complete Match

Let's test when all blocks have corresponding containers:

const blocks2 = [
   { id: 1 },
   { id: 2 },
   { id: 3 },
]
const containers2 = [
   { block: { id: 1 } },
   { block: { id: 2 } },
   { block: { id: 3 } },
   { block: { id: 5 } }, // Extra container is fine
]

console.log(checkPropertyModern(blocks2, containers2));
true

Comparison

Method Readability Performance
Traditional Loops More verbose Can exit early
Array Methods More concise Functional approach

Conclusion

Both approaches work effectively for comparing arrays of objects. The modern array methods provide cleaner, more readable code, while traditional loops offer explicit control over execution flow.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements