Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda