Left rotate array using javascript

Left rotate array using javascript

 Rotate array by d digits using javascript 

Method 1 using shift() and push()


function rotateLeft(d, arr) {
      //loop through the d times
    for( let i = 0 ; i < d ; i++ ) {
        //shift removes first element from the array
        const removedElement =  arr.shift();
         // push() adds removed element to the end of array
         arr.push(removedElement);
    }
    return newArray;
}

console.log(rotateLeft(2, [2, 5, 6, 7, 8]));

Method 2 using ES6 Spread Operator and Slice() – one liner

const rotLeft = (arr, d) => [...arr.slice(d), ...arr.slice(0, d)];
console.log(rotLeft([2, 5, 6, 7, 8], 2));