
- 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
Write an algorithm that takes an array and moves all of the zeros to the end 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]
- Related Articles
- How do I write a function that takes an array of values and returns an object JavaScript?
- Move All the Zeros to the End of Array in Java
- Move all zeros to start and ones to end in an Array of random integers in C++
- In-place Algorithm to Move Zeros to End of List in JavaScript
- Adding an element at the end of the array in Javascript
- Removing an element from the end of the array in Javascript
- How to move all the zeros to the end of the array from the given array of integer numbers using C#?
- JavaScript Return an array that contains all the strings appearing in all the subarrays
- Algorithm to dynamically populate JavaScript array with zeros before and after values
- Take an array of integers and create an array of all the possible permutations in JavaScript
- Algorithm to get the combinations of all items in array JavaScript
- Summing all the unique values of an array - JavaScript
- Moving all zeroes present in the array to the end in JavaScript
- Sum of all the non-repeating elements of an array JavaScript
- Looping through and getting frequency of all the elements in an array JavaScript

Advertisements