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

153
Visualizações
Function return true based on name index in an array

I have a 2d array like this:

  const sample = [
    ['', 'Name 1', ''],
    ['Name 2', '', 'Name 3'],
    ['', 'Name 4', 'Name 5']
  ]

I'm trying to write a function to return true if the index of input name is either 0 or 1 otherwise return false.

I have this:

  function isIndexZeroOrOne(arr, name) {
    for (const row of arr) {
        const i = row.indexOf(name)
        return i === 0 || i === 1 ? true : false      
    }
  }

However, it only seems to work for the first sub array in sample (i.e., sample[0])

It's not working for Name 2: console.log(isIndexZeroOrOne(sample, 'Name 2')) It return false even though it should be true (because the index of Name 2 is 0)

What am I doing wrong?

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

0

The return statement ends the loop and exits the function, so you're only checking the first subarray.

You should only return immediately when the condition matches, not when it fails, so you continue testing other array elements.

function isIndexZeroOrOne(arr, name) {
  for (const row of arr) {
    const i = row.indexOf(name)
    if (i === 0 || i === 1) {
      return true;
    }
  }
  return false;
}

Or use the some() method.

function isIndexZeroOrOne(arr, name) {
  return arr.some(el => el[0] === name || el[1] === name);
}

about 4 years ago · Juan Pablo Isaza Relatório

0

I think it's the way that you've written the ternary. It's evaluating things like this:

return (i === 0) || (i === 1 ? true : false) 

It would be better to do:

if (i=== 1 || i === 0) return true

At the moment, you are only ever checking the first row because you always return true or false.

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