Trying to remove all 0's from an array and return them in the same array
So for example if I have this as an array
let arrThree = [9,0,9,1,2,1,1,3,1,9,0,0,9,0,0,0,0,0,0,0]
I would get this:
let arrThree = [9,9,9,1,2,1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0,0]
This is what I wrote:
var remove = function (arr) {
let test = [];
for(let i = 0; i < arr.length; i++){
arr[i] === 0 ? test.push(arr.splice(i,1)) : false //if i is 0 then we want to push that into another array
}
arr.push(...test)
return [].concat(...arr)
}
When I run this function I get this
[
9, 9, 1, 2, 1, 1, 3,
1, 9, 0, 9, 0, 0, 0,
0, 0, 0, 0, 0, 0
]
Not sure where I am going wrong?
splice, that skips an index on the next iteration becausearr.lengthis one shorter -- all of the elements afterihave moved 1 forward to fill its spot. Usei--whenever you splice or loop in reverse. Also,splicehere is O(n), so this is an unnecessarily quadratic solution. See the linked dupe suggestion for a variety of linear solutions.arrThree.filter(i => i != 0).concat(arrThree.filter(i => i == 0))testarray and do:if (arr[i] === 0) arr.push(arr.splice(i,1)[0]);This will not change the length so theforloop still works.