Check if an array of object is exactly equal to another array that contains one of its property

I have these 2 arrays
The first one is fixed and does not change and contains the id of the 2nd array:

fixed=["123","456","789"] 

The second can change

variableArray=[{name:"Joe",id:"123"},{name:"Joe",id:"456"},{name:"Joe",id:"789"}]

I want to return true if, even if there were some changes at the end the variable array is the same length and contains exactly the same keys of the "fixed"

NOT VALID:

fixed=["123","456","789"] 
variableArray=[{name:"Joe",id:"456"},{name:"Joe",id:"789"}] 

return false because is missing the id "123" (and the length is also different so is excluded by default)

NOT VALID:

fixed=["123","456","789"] 

variableArray=[{name:"Joe",id:"123"},{name:"Joe",id:"456"},{name:"Joe",id:"001"}]

this will return false because, even if contains 3 elements as there are in the "fixed" is missing the id "789" and have another "001" instead

>Solution :

as @mplungjan mentiond, you can use Every:

let fixed = ["123", "456", "789"];
let variableArray1 = [{
  name: "Joe",
  id: "123"
}, {
  name: "Joe",
  id: "456"
}, {
  name: "Joe",
  id: "789"
}];
let variableArray2 = [{
  name: "Joe",
  id: "123"
}, {
  name: "Joe",
  id: "456"
}, {
  name: "Joe",
  id: "001"
}]


let containsAll1 = variableArray1.every(elem => fixed.includes(elem.id));
let containsAll2 = variableArray2.every(elem => fixed.includes(elem.id));

console.log(containsAll1, containsAll2);

Leave a Reply