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

149
Visualizações
Getting the first item with a condition in an array returned asynchronously in JavaScript

I have a function called getItems that returns an array of objects asynchronously. Each object has a isOccupied method that returns a boolean.

I wrote a function that takes an index and returns whether index-th item in the array's isOccupied is true or false.

I wrote a function to return the index of the item from the array returned by getItems.

    async getOccupiedItemIndex() {
      let selectedIdx = 0;
      return getItems().then(items => {
        items.forEach((item, index) => {
          if (item.isOccupied()) selectedIdx = index;
        });
        return selectedIndex;
      });
    }

I want to improve this function because

  1. The fact that we are using an async function to use an array makes it lengthy.

  2. I see that if there is no item found, it could return null?

  3. We can assume that there will only be one occupied item in the array.

Any thoughts on improving this?

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

0

You could use Array.findIndex() :

const getOccupiedItemIndex = () => 
      getItems().then( items => items.findIndex( item => item.isOccupied() ) )

will find first occupied index or -1 if not found

about 4 years ago · Juan Pablo Isaza Relatório

0

You could return the right variable. selectedIndex isn't declared. Only selectedIdx is.

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