

- 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
In-place Algorithm to Move Zeros to End of List in JavaScript
Suppose we are given an array of integers, lets say arr. We are required to write a function that puts all the zeros to the back of the array by modifying the list in-place.
The function should do this in such a way that the relative ordering of other elements should stay the same.
For example −
If the input array is −
const arr = [0, 11, 0, 22, 67];
Then the array should be modified to −
const output = [11, 22, 67, 0, 0];
Example
Following is the code −
const arr = [0, 11, 0, 22, 67]; const moveZeroToEnd = (arr = []) => { const swap = (array, ind1, ind2) => { const temp = array[ind1]; array[ind1] = array[ind2]; array[ind2] = temp; }; let j = 0; for (let i = 0; i < arr.length; ++ i) { if (arr[i] !== 0) { swap(arr, i, j++); } } while (j < arr.length) { arr[j++] = 0; }; }; moveZeroToEnd(arr); console.log(arr);
Output
Following is the console output −
[11, 22, 67, 0, 0]
- Related Questions & Answers
- In-place Move Zeros to End of List in Python
- Move all zeros to the front of the linked list in C++
- Move all zeros to start and ones to end in an Array of random integers in C++
- Move first element to end of a given Linked List in C++
- Write an algorithm that takes an array and moves all of the zeros to the end JavaScript
- Move all zeroes to end of the array using List Comprehension in Python
- Move all zeroes to end of array in C++
- How to move all the zeros to the end of the array from the given array of integer numbers using C#?
- Algorithm to dynamically populate JavaScript array with zeros before and after values
- Move the first row to the end of the JTable in Java Swing
- Minimum move to end operations to make all strings equal in C++
- C++ program to find minimum number of steps needed to move from start to end
- Double the first element and move zero to end in C++ Program
- An in-place algorithm for String Transformation in C++
- How to move the pointer of a ResultSet to the end of the table using JDBC?
Advertisements