-1

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

spring00
  • 177
  • 1
  • 4
  • 13
  • [Array.every](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) – mplungjan Nov 07 '21 at 13:18

1 Answers1

1

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);
Rafael Herscovici
  • 16,558
  • 19
  • 65
  • 93