Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove undefined and create a new array Javascript?

I have the following array:

var imagesList = [undefined x 1, cars.jpg, undefined x 1, boats.jpg];

How do I filter out the undefined? so I can get it as follows:

var imagesShow = [cars.jpg, boats.jpg];

I have not found much documentation on getting rid of undefined in an array using javascript.

like image 274
ticktock Avatar asked Nov 28 '22 06:11

ticktock


2 Answers

You could use Array#filter with Boolean as callback for truthy values.

var imagesList = [undefined, 'cars.jpg', undefined, 'boats.jpg'],
    imagesShow = imagesList.filter(Boolean);
    
console.log(imagesShow);
like image 170
Nina Scholz Avatar answered Dec 10 '22 03:12

Nina Scholz


Use Array#filter:

var imagesList = [undefined, 'cars.jpg', undefined, 'boats.jpg'];

var result = imagesList.filter(function(v) {
  return v !== undefined;
})

console.log(result);
like image 41
Ori Drori Avatar answered Dec 10 '22 02:12

Ori Drori