Move 0's in the front and non-zeroes at the end

1 min read
Table of contents

const numbers = [1, 0, 3, 4, 0, 0, 5, true, "js", 2, 0, 7, 0, 9, false, 0];
function moveAllZeroesToFront () {
return [...numbers.filter(item => !item && Number(item) === item),
...numbers.filter(item => item !== 0)];
}
const arr = moveAllZeroesToFront(numbers);
console.log(arr);
Output:
[
0, 0, 0, 0, 0, 0, 1, 3, 4, 5, true, 'js', 2, 7, 9, false
]
0
Subscribe to my newsletter
Read articles from Hari Krishna Anem directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Hari Krishna Anem
Hari Krishna Anem
Full stack developer (ReactJS, NodeJS, JavaScript, PHP, SQL)