Home > Software design >  How to remove undefined from a list of items?
How to remove undefined from a list of items?

Time:08-29

How to prevent appearing undefined in the output?

var item1 = $(result).find('.item:nth-child(2) a').html(),
    item2 = $(result).find('.item:nth-child(3) a').html(),
    item3 = $(result).find('.item:nth-child(4) a').html(),
    item4 = $(result).find('.item:nth-child(5) a').html();

$('div').html(item1 item2 item3 item4);

CodePudding user response:

You could put them all in an array and then filter it.

const array = [item1, item2, item3, item4];
const onlyDefined = array.filter(item => item !== undefined);

If you're not doing anything else with the variables, you could also do it all in chunk, by looping over the numbers 2 through 5.

CodePudding user response:

var item1 = $(result).find('.item:nth-child(2) a').html(),
item2 = $(result).find('.item:nth-child(3) a').html(),
item3 = $(result).find('.item:nth-child(4) a').html(),
item4 = $(result).find('.item:nth-child(5) a').html();

item1 = typeof item1 === 'undefined' ? '' : item1;
item2 = typeof item2 === 'undefined' ? '' : item2;
item3 = typeof item3 === 'undefined' ? '' : item3;
item4 = typeof item4 === 'undefined' ? '' : item4;

$('div').html(item1 item2 item3 item4);

CodePudding user response:

You can use Nullish coalescing operator to set a default value to prevent undefined values in your code:

const item = undefined ?? "";
//output: ""

or You can filter them:

const items = [undefined, "Hello", undefined, " World!"];
const filtereditems = items.filter(x=>x); 

const joindItems= filtereditems.join(""); 
//output: 'Hello World!'
  • Related