

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 Questions & Answers
- How do I write a function that takes an array of values and returns an object JavaScript?
- 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
- JavaScript Return an array that contains all the strings appearing in all the subarrays
- How to move all the zeros to the end of the array from the given array of integer numbers using C#?
- Take an array of integers and create an array of all the possible permutations in JavaScript
- Golang program to create an integer array that takes inputs from users.
- Summing all the unique values of an array - JavaScript
- JavaScript function that takes a multidimensional and a single array, and finds matches of the single array in the multi-d array
- Algorithm to get the combinations of all items in array JavaScript
- Algorithm to dynamically populate JavaScript array with zeros before and after values
- Function that returns the minimum and maximum value of an array in JavaScript
- Sum of all the non-repeating elements of an array JavaScript
Advertisements