Thursday, May 20, 2021

Javascript Practice 55: JS Hero - Array: shift() and push()

 
Question: 

Write a function rotate that rotates the elements of an array. All elements should be moved one position to the left. The 0th element should be placed at the end of the array. The rotated array should be returned.

Example: rotate(['a', 'b', 'c']) should return ['b', 'c', 'a'].




Answer: 

function rotate (array) {

let firstEl = array.shift();
array.push(firstEl);
return (array); 

}




> we declare a function rotate
> it has one parameter array
> we declare a variable firstEl 
> we initialize it with a value of an array on which we have used the shift method
> this method changes the length of the array 
> the shift method removes the first element from an array and returns that removed element
> it also shifts all other elements to a lower index
> we then use the push method on the array 
> we push the 'firstEl' variable where we stored the first element which we removed from the same array
> the push method will add the first element that we removed to the end of the array
> we then return the array and get our result

No comments:

Post a Comment