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

93
Visualizações
Check if first item in array is empty value

I have seen dozens of questions asked for checking if an array is empty. But I can't find the question on how to check if the first item in an array is empty.

Currently, I am doing this check on this way, but I highly doubt that it is the correct way to do this.

var specialtiesListArray = ['', 'not', 'empty', 'value'];

if (specialtiesListArray[0] == '') {
    
    specialtiesListArray.shift(); // <== Removing the first item when empty.

}

console.info({ specialtiesListArray });

The above works fine, but I am wondering is this ok? Are there better ways. And if someone knows a duplicate, then please let me know. I gladly delete the question if it has already been answered.

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

0

I think your approach is just fine. You could create a function, and check array length before trying to read element at index 0:

  • utils.js

export const removeFirstItemIfEmpty = (array) => {
    if (array.length > 0 && array[0] == '') {
        array.shift();
    }
    return array;
}

import { removeFirstItemIfEmpty } from './utils.js'

const result = removeFirstItemIfEmpty(['', 'not', 'empty', 'value']);
console.info({ result });
about 4 years ago · Juan Pablo Isaza Relatório

0

You could use filter and update the array.

specialtiesListArray = ['', 'not', 'empty', 'value'];
specialtiesListArray = specialtiesListArray.filter((item, index) => index!==0 && item !== '');
console.log(specialtiesListArray);

about 4 years ago · Juan Pablo Isaza Relatório

0

The following function will remove anything that is undefined, null or empty but will allow the number 0 to pass:

var testArr = [['', null, 'not', 'empty', 'value'],[false,2,3,4],[undefined,"", null,"one","two"],[0,1,2,3]];

function ltrimArr(arr){
 while (arr.length && !arr[0]&&arr[0]!==0) arr.shift();
 return arr
}

testArr.forEach(a=>console.log(ltrimArr(a)))

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