DEV Community

rogerdavid2
rogerdavid2

Posted on

Move first index value to the last index while maintaining original order on an array.

Assume we have an array [5, 3, 7, 8] such that the first index value is moved to the back while preserving the original order resulting in [3, 7, 8, 5]

Let's consider what we need to accomplish this. First, an array: let values = [5, 3, 7, 8]; we will be announcing values as list because list is the named parameter for the function further along.

With a for loop we will be traversing over an array to perform changes.

A for loop can be broken into three parts.

for (initialization; test; update) {
      statements....
}
Enter fullscreen mode Exit fullscreen mode

However, let's dissect our for loop. For our initialization let's start at zero since arrays start with an index at zero. let i = 0;

 0  1  2  3
[5, 3, 7, 8] // length is 4
Enter fullscreen mode Exit fullscreen mode

Our test will evaluate when i is less than the list’s length minus one. That is because our array [5, 3, 7, 8] has a length of four, yet we only want to shift three values, but not including the number five. Yielding in i < list.length - 1; and update is represented by i++

for (let i = 0; i < list.length - 1; i++) {

}
Enter fullscreen mode Exit fullscreen mode

Now let's think about our three values that are going to get shifted.

 0  1  2  3
[5, 3, 7, 8] // Original Array; Length 4

 0  1  2  3
[3, 7, 8, 5] // Shifted Array; Length 4

Enter fullscreen mode Exit fullscreen mode

Shift = Original
list[0] = list[1];
list[1] = list[2];
list[3] = list[4];

Generally described as:
list[i] = list[i + 1];

The list first index value will be placed in a variable let idx = list[0]; So idx will be declared before the for loop since we are only shifting the remaining three values.

After the for loop is done iterating we will type list[list.length - 1] = idx; to store idx into list’s last index. After, we can wrap all the code in a function called shiftLeft which will take an array as a parameter.

Our final code is:

"use strict";

let values = [5, 3, 7, 8];
console.log(values) // [5, 3, 7, 8];

function shiftLeft(list) {
    let idx = list[0];
    for (let i = 0; i < list.length - 1; i++) {
        list[i] = list[i + 1]
    }
    list[list.length - 1] = idx;
    console.log(list) 
}

shiftLeft(values); // [3, 7, 8, 5];
Enter fullscreen mode Exit fullscreen mode

Top comments (0)