
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
How to remove blank (undefined) elements from JavaScript array - JavaScript
Suppose we have an array of literals like this −
const arr = [4, 6, , 45, 3, 345, , 56, 6];
We are required to write a JavaScript function that takes in one such array and remove all the undefined elements from the array in place. We are only required to remove the undefined and empty values and not all the falsy values.
Use a for loop to iterate over the array and Array.prototype.splice() to remove undefined elements in place.
Example
Following is the code −
const arr = [4, 6, , 45, 3, 345, , 56, 6] const eliminateUndefined = arr => { for(let i = 0; i < arr.length; ){ if(typeof arr[i] !== 'undefined'){ i++; continue; }; arr.splice(i, 1); }; }; eliminateUndefined(arr); console.log(arr);
Output
This will produce the following output in console −
[ 4, 6, 45, 3, 345, 56, 6 ]
- Related Articles
- Remove elements from array using JavaScript filter - JavaScript
- How to remove duplicate elements from an array in JavaScript?
- How to check for null, undefined, or blank variables in JavaScript?
- How to remove certain number elements from an array in JavaScript
- How to remove all blank objects from an Object in JavaScript?
- Remove '0','undefined' and empty values from an array in JavaScript
- How to find the biggest number in an array around undefined elements? - JavaScript
- Remove elements from array in JavaScript using includes() and splice()?
- JavaScript - array undefined element count
- How to redundantly remove duplicate elements within an array – JavaScript?
- Remove elements from Javascript Hash Table
- How to remove elements from an array until the passed function returns true in JavaScript?
- Remove elements from a queue using Javascript
- Remove elements from a PriorityQueue using Javascript
- Remove elements from a Set using Javascript

Advertisements