Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird bug in Javascript splice method

I have an array which contains "Zeros" and I want to move all of the "Zeros" to the last indexes of the array.

The expected output is:

[1,2,3,0,0,0,0]

But instead I get:

[1,2,0,3,0,0,0]

let a = [0, 1, 2, 0, 0, 3, 0];
let count = 0;
let len = a.length;

for (i = 0; i < len; i++) {
  if (a[i] == 0) {
    count = count + 1;
    a.splice(i, 1);
  }
}

for (j = 0; j < count; j++) {
  a.push(0);
}

console.log(a);
like image 767
Faizal Mohaideen Kadersha Avatar asked Jun 30 '19 18:06

Faizal Mohaideen Kadersha


People also ask

Why is splice not working JavaScript?

It's not working because you are removing items from the array while looping through the keys. When you remove an item, it will rearrange the other items depending on how the array is implemented internally, and you end up with a loop that doesn't iterate over the keys that you expect.

Is JavaScript splice destructive?

The . splice() method is a destructive array method, which means it modifies the array on which it is called (disclaimer: destructive methods can be risky, especially if you use the array in question elsewhere in your program, so proceed with caution).

What does the splice method do in JavaScript?

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

What is the Fuentionality of splice method in JavaScript?

splice() JS Array Method. The splice() method is a built-in method for JavaScript Array objects. It lets you change the content of your array by removing or replacing existing elements with new ones. This method modifies the original array and returns the removed elements as a new array.


1 Answers

When you remove the item from the array all the element shift down by one. When you advance your index (i++), you skip the shifted down item in the array which happens to be successive zero in the array.

Solution: Do the for next loop backward and it'll work.

like image 52
John Avatar answered Sep 25 '22 22:09

John