How to shift array elements to left by one position in Node.js

2 Answers

0 votes
function ShiftArrayToLeft(arr) {
    const size = arr.length;
         
    let temp = arr[0];
     
    for (let i = 0; i < size - 1; i++) {
        arr[i] = arr[i + 1];
    }
     
    arr[size - 1] = temp;
}
 
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
ShiftArrayToLeft(arr);
 
console.log(arr);
 
 
 
 
/*
run:
 
[ 2, 3, 4,  5, 6, 7, 8, 9, 10, 1 ]

*/

 



answered Sep 12, 2022 by avibootz
0 votes
function ShiftArrayToLeft(arr) {
    let first = arr.shift();
     
    arr.push(first);
     
    return arr;
}
 
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
ShiftArrayToLeft(arr);
 
console.log(arr);
 
 
 
 
/*
run:
 
[ 2, 3, 4,  5, 6, 7, 8, 9, 10, 1 ]

*/

 



answered Sep 12, 2022 by avibootz
...