简体   繁体   中英

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.

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--){ 

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)
    }
var arrNum = [0,0,0,1];
var result = [];

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

console.log(result);

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)
}

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)
})

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.

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/

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM