
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Blank and Undefined Elements from JavaScript Array
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 ]
Advertisements