We can do better.
The above snippet would get the job done, but requires extra space with the new temp
array.
Without a temp
array, we'll need to change the position of elements in the array in-place. This means that we'll need to mutate the array's elements directly. This requires us to keep track of indexes.
xxxxxxxxxx
const arr = [1, 0, 2, 0, 4, 0];
const nonZeros = [1, 2, 4]
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment