Skip to main content

Command Palette

Search for a command to run...

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

Published
1 min read
Move 0's in the front and non-zeroes at the end
H

Full stack developer (ReactJS, NodeJS, JavaScript, PHP, SQL)

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
]

Execute above code here