Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!