JavaScript tips — Remove undefined values from an array

Publié le: 06 octobre 2022
sur la chaîne: Code 2020
2,597
14

The built-in filter method on #javascript arrays makes it easy to remove undefined values.

To only removed undefined values, use:

myArray.filter(function(x) { return x !== undefined; });

This will return a new array with all undefined values from 'myArray' removed. This does not modify the original array.

If you search online, you may see other resources suggesting doing this using:

myArray.filter(function(x) { return x; });

or

myArray.filter(Boolean);

These approaches may not be what you want as they will remove every falsy value from the array (such as 0, empty strings, and false) along with the undefined values

https://developer.mozilla.org/en-US/d...


Sur cette page du site, vous pouvez voir la vidéo en ligne JavaScript tips — Remove undefined values from an array durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur Code 2020 06 octobre 2022, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 2,597 fois et il a aimé 14 téléspectateurs. Bon visionnage!