0

I am trying to move an array to the right by a set value, and replacing the now missing spaces with 0. I just can not figure out how to do it.

Array before moving:

let array = [1,2,3,4,5,6,7]

Array after moving 2 to the right:

array = [0,0,1,2,3,4,5]

Ive looked at other stack overflow posts but those just wrap around the data making a move to the right look like this:

array = [6,7,1,2,3,4,5]

Whilst I want to just remove the 6 and 7.

Samo2120
  • 179
  • 1
  • 2
  • 11

2 Answers2

2

Just unshift with 0's and the pop off the last numbers.

function shiftArray(arr, numberOf0s) {
  for (let i = 0; i < numberOf0s; i++) {
    arr.unshift(0);
    arr.pop();
  }
}

function shiftArray(arr, numberOf0s) {
  for (let i = 0; i < numberOf0s; i++) {
    arr.unshift(0);
    arr.pop();
  }
  return arr;
}

let array = [1,2,3,4,5,6,7];

console.log(array);

shiftArray(array, 2);

console.log(array);
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
1

As with most languages manipulating an array type data structure anywhere other than the back via methods like insert, unshift is not ideal. This is because of the way elements of an array are stored in memory i.e., contiguously. For this reason, each insert or unshift operation requires moving all the elements after it every time to maintain this "contiguousness". Basically, you should avoid using these methods unless you absolutely have to when working with arrays.

Luckily in this case you can just iterate over the array in reverse and copy the element to its correct position and fill in the remaining slots with zeros for an O(n) solution where n is the length of the array:

const moveToRight = (array, n) => {
    if (array === undefined || array.length == 0) {
        return;
    }
    if (n < 0) {
        throw 'Error n cannot be negative!';
    }
    let i = array.length - 1;
    while (i >= 0 + n) {
        array[i] = array[i - n];
        i--;
    }
    while (i >= 0) {
        array[i] = 0;
        i--;
    }
    return;
}

array = [1, 2, 3, 4, 5, 6, 7];
try {
    moveToRight(array, 2);
} catch (e) {
    console.error(e);
}
console.log(array);
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40