So I have an array of objects to iterate over, on every iteration I need to check if a key named blocks has or has no length.
If all of the blocks keys are empty (length === 0) then I need to do an operation, otherwise do not. Get it? If ONNLY ONE blocks key has a length > 0 then the operation should be avoided.
for (let i = 0; i < blockColumns.length; i++) {
if (!blockColumns[i].blocks.length) {
// TRIGGER OPERATION
}
}
In the code above the problem is that the operation will be trigger when at least one blocks key has no length, which what I don't need. The operation should be trigger ONLY when all of the blocks keys have length === 0.
Use Array.every() to check that every item has a 0 length (!0 === true). If all items have 0 length, the every would return true. If a false is encountered (ie length > 0), every would return false immediately.
const allEmpty = blockColumns.every(o => !o.blocks.length)
if(allEmpty) doSomething()
This sounds like something that Array.prototype.every would be useful for:
if (blockColumns.every((el) => el?.blocks?.length === 0)) {
// Do your operation
}
I've used optional chaining here since I'm not sure if there might be a case where an element doesn't have a blocks property, or if that property may not have a length property. But depending on how confident you can be in your data structure, you may not need to do that.
well then you can do
x = 0
for (let i = 0; i < blockColumns.length; i++) {
if (!blockColumns[i].blocks.length > 0) {
x+=1;
}
}
if(x == blockColumns.length){
//do something
}
this is a very simple way of doing it and i don't think that it's efficient at all but it gets the job done for now :D