Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if objects are in an array based on a value in JavaScript?

Tags:

javascript

For example, how do I check if ALL the objects in array2 exist in array1 based on their id?

const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]
const array2 = [{ id: 1 }, { id: 2 }]

For some reason, I couldn't find the solution on Google.

I thought about this:

const result = array1.every(obj1 => {
  // what do use here? includes? contains?
})

console.log(result)

But I'm kind of stuck in the middle of the code. The most logical solution to me was to use includes. However, includes doesn't seem to take a function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes. So I'm not sure if I can check the objects by id.

like image 755
alex Avatar asked Feb 28 '26 01:02

alex


2 Answers

includes will only be true if both objects are the same reference in memory, which is (probably) not the case. Instead, I'd create a Set of array1's ids initially, and then check to see if every array2 id is in the set. This way, you only have to iterate over array1 once, at the very beginning (Sets have O(1) lookup time):

const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
const array2 = [{ id: 1 }, { id: 2 }];

const idSet = new Set(array1.map(({ id }) => id));
console.log(
  array2.every(({ id }) => idSet.has(id))
);

(Arrays do not have a contains function)

like image 200
CertainPerformance Avatar answered Mar 02 '26 15:03

CertainPerformance


var matching = [];

for (var j = 0; j < array1.length; j++) {
    for (var i = 0; i < array2.length; i++) {
        if (array2[i].id === array1[j].id) {
            matching.push(array2[i].id);       
        }
    }
}

if (array2.length === matching.length) {
    console.log("All elements exist");
} else {
    console.log("One or more of the elements does not exist");
}
like image 23
Snezhana Avatar answered Mar 02 '26 15:03

Snezhana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!