Home > Blockchain >  Check if first item in array is empty value
Check if first item in array is empty value

Time:05-25

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.

CodePudding user response:

You could use filter and update the array.

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

CodePudding user response:

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 });

CodePudding user response:

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)))

  • Related