Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
How can I check that a specific key in an array is empty at every index?

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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

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()
about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda