
- 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
Moving all zeroes present in the array to the end in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of literals that might contain some 0s. Our function should tweak the array such that all the zeroes are pushed to the end and all non-zero elements hold their relative positions.
Example
Following is the code −
const arr = [5, 0, 1, 0, -3, 0, 4, 6]; const moveAllZero = (arr = []) => { const res = []; let currIndex = 0; for(let i = 0; i < arr.length; i++){ const el = arr[i]; if(el === 0){ res.push(0); }else{ res.splice(currIndex, undefined, el); currIndex++; }; }; return res; }; console.log(moveAllZero(arr));
Output
Following is the console output −
[ 5, 1, -3, 4, 6, 0, 0, 0 ]
- Related Articles
- Move all zeroes to end of array in C++
- Move all zeroes to end of the array using List Comprehension in Python
- Moving all vowels to the end of string using JavaScript
- Sum of all positives present in an array in JavaScript
- Move All the Zeros to the End of Array in Java
- Moving all Upper case letters to the end of the String using Java RegEx
- Picking all the numbers present in a string in JavaScript
- How to store all dates in an array present in between given two dates in JavaScript?
- Moving all special char to the end of the String using Java Regular Expression RegEx)
- Write an algorithm that takes an array and moves all of the zeros to the end JavaScript
- Adding an element at the end of the array in Javascript
- Removing an element from the end of the array in Javascript
- Shifting certain elements to the end of array JavaScript
- Sorting an array including the elements present in the subarrays in JavaScript
- Beginning and end pairs in array - JavaScript

Advertisements