Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading