I'm currently learning JS and doing some problems on Codewars. I've written a function to solve a problem, but I don't understand why the for loop in JS behaves the way it does in my solution, I'd be glad if anyone could help me. The problem is as follows:
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
moveZeros([1, 2, 0, 1, 0, 1, 0, 3, 0, 1]) // returns[1, 2, 1, 1, 3, 1, 0, 0, 0, 0]
My solution is:
var moveZeros = function(arr) {
let newarr = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 0) {
newarr.push(arr[i])
} else {
newarr.unshift(arr[i])
};
}
return newarr;
}
What my function returns is:
[1, 3, 1, 1, 2, 1, 0, 0, 0, 0]
Why does JS put 3 before 2, although its index in the array is 7?
Thanks in advance!
pushinstead (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)