Got a algorithm problem that shifts zeroes to the end of an array without making a new array. This naïve solution doesn’t work because it doesn’t like the idx++. I’m confused because I’m incrementing the idx AFTER the swap. Anyone know why this is happening?
function zeroesToEnd(a) {
const numOfZeores = a.filter((i) => i === 0).length;
let idx = a.length - numOfZeores;
for (let i = 0; i < a.length; i++) {
let curr = a[i];
if (curr === 0) {
let temp = a[i];
a[i] = a[idx];
a[idx] = temp;
idx++; //Won't let me do this
}
}
return a;
}
console.log(zeroesToEnd([1, 2, 0, 0, 4, 0, 5]));