
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
Move All Zeros to the End of an Array in JavaScript
We have to write a function that takes in an array and moves all the zeroes present in that array to the end of the array without using any extra space. We will use the Array.prototype.forEach() method here along with Array.prototype.splice() and Array.prototype.push().
The code for the function will be −
Example
const arr = [34, 6, 76, 0, 0, 343, 90, 0, 32, 0, 34, 21, 54]; const moveZero = (arr) => { for(ind = 0; ind < arr.length; ind++){ const el = arr[ind]; if(el === 0){ arr.push(arr.splice(ind, 1)[0]); ind--; }; } }; moveZero(arr); console.log(arr);
Output
The output in the console will be −
[34, 6, 76, 343, 90, 32, 34, 21, 54, 0, 0, 0, 0]
Advertisements