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!
Well unshift()
pushes the value in front of array.
Have a look at this example.ti understand how unshift()
works.
let a = [];
a.unshift(1);
a.unshift(2);
a.unshift(3);
a.unshift(4);
console.log(a);
Push
add values at the back of array.
look at example below to understand how push works.
let a = [];
a.push(1);
a.push(2);
a.push(3);
a.push(4);
console.log(a);
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;
}
let op = moveZeros([1, 3, 1, 1, 2, 1, 0, 0, 0, 0]);
console.log(op);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With