Skywalker
Skywalker

Reputation: 5194

Array Splice - Javascript

Its a very small issue and for the life of me I can't figure out what it is. My brain has locked itself from thinking. I need someone else to have a look this code.

The output of the code should be: [1,0,0,0]

UPDATE:

The function should be able to read an array of numbers and if it finds any zeros within the array it should move them to the end of the array.

The output of the code keeps coming as: [0,1,0,0]

var arrNum = [0,0,0,1];

function test() {
   for(var i=0; i<arrNum.length; i++){

 if(arrNum[i] == 0){

    arrNum.splice(i,1)
    arrNum.splice(arrNum.length, 1, 0)

    }
 }
 return alert(arrNum)
}

Here is a working plunker.

Apologies for this, I know the issue is something very small but my brain has stopped working now and I need a fresh pair of eyes.

Upvotes: 0

Views: 252

Answers (9)

Oliver Pulges
Oliver Pulges

Reputation: 111

As the operation you want to do is actually sorting, for readability and compactness of code maybe you should be doing this instead:

var arrNum = [0,1,0,0]; 
arrNum.sort(function(a, b) {
  return a == 0 ? 1 : 0;
});

It can contain any number and will keep order of others than 0

Upvotes: 0

Artur Aleksanyan
Artur Aleksanyan

Reputation: 500

The problem was you are modifying an array while looping over it in if statement.

Here is a working plunker of your example.

var len = arrNum.length;
var index = 0;

while(len) {

    if(arrNum[index] == 0) {
        arrNum.splice(index,1);
        arrNum.push(0);
    } else {
        ++index;
    }

    --len;
}

Upvotes: 0

TrojanMorse
TrojanMorse

Reputation: 642

A nice little way using Objects - busy learning them so just posting a variation of deligation

var methods = {
    moveZero: function(arr){
        //console.log(arr);
        var newArr = [];
        for(var i  = 0; i < arr.length; i++){
            if(arr[i] === 0){
                newArr.push(arr[i]);
            }else{
                newArr.unshift(arr[i]);
            }
        }
        console.log(newArr);
    }
}

var arrNum = Object.create(methods);
arrNum.moveZero([0,0,50,56,85,0,0,43,10,0,1]);

JSFiddle - https://jsfiddle.net/ToreanJoel/qh0xztgc/1/

Upvotes: 0

Fabiano
Fabiano

Reputation: 5199

Why don't you use a temporary array to help? The problem with your code is that the splice() function modifies the original array, and you are doing it inside the loop.

The code below produces what you need:

var arrNum = [0,0,0,1];
var arrResult = new Array();

function test() {

   for(var i=arrNum.length-1; i>=0; i--)
   {
        arrResult.push(arrNum[i]);
   }

   arrNum = arrResult;
   return alert(arrNum);
}

With another array to store the new values, you gain flexibility to do whatever you need with the data of the first array.

Upvotes: 0

Daniel Shin
Daniel Shin

Reputation: 5206

Prefer built-in functions every time possible.

var output = [];
[0,0,0,1].forEach(function(num) {
  if(num == 0) output.push(0);
  else output.unshift(num)
})

Upvotes: 0

epascarello
epascarello

Reputation: 207501

With the way you have it written, you need to loop in the reverse order. You end up skipping indexes when you remove the index. Looping in the reverse direction keeps you from skipping them.

for(var i=arrNum.length-1; i>=0; i--){ 

Upvotes: 5

Oliver Pulges
Oliver Pulges

Reputation: 111

You are iterating with index i = 0,1,2,3 and at the same time removing first elements of array. So your iteration can not see the 1, it jumps over as it is moved to already iterated index. Easiest would be to just reverse the loop to bypass the issue.

var arrNum = [0,0,0,1];

function test() {
  for(var i= arrNum.length; i >= 0; i--){

    if(arrNum[i] == 0){
      arrNum.splice(i,1)
      arrNum.splice(arrNum.length, 1, 0)
    }
  }
  return alert(arrNum)
}

Upvotes: 0

Yuriy Yakym
Yuriy Yakym

Reputation: 3911

var arrNum = [0,0,0,1];
var result = [];

arrNum.forEach(function(v) {
    !!v ? result.unshift(v) : result.push(v);
});

console.log(result);

Upvotes: 0

An0nC0d3r
An0nC0d3r

Reputation: 1303

You can use unshift() to insert at beginning of an array and push() to the end...

    var arrNum = [0,0,0,1];
    var output = [];

    function test() 
    {
       for(var i=0; i<arrNum.length; i++)
       {
         if(arrNum[i] == 0)
            output.push(0);
         else
            output.unshift(arrNum[i]);
     }
     return alert(output)
    }

Upvotes: 0

Related Questions