DefNotBruceWayne
DefNotBruceWayne

Reputation: 89

Rotate the elements of an array to the left

I am trying to solve a JavaScript challenge from jshero.net. The challenge is this:

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. rotate(['a', 'b', 'c']) should return ['b', 'c', 'a'].

All I could come up with was this:

function rotate(a){
  let myPush = a.push();
  let myShift = a.shift(myPush);
  let myFinalS = [myPush, myShift]
  return myFinalS
}

But the error message I got was:

rotate(['a', 'b', 'c']) does not return [ 'b', 'c', 'a' ], but [ 3, 'a' ]. Test-Error! Correct the error and re-run the tests!

I feel like I'm missing something really simple but I can't figure out what. Are there other ways to solve this?

Upvotes: 2

Views: 1850

Answers (5)

tusharkashyap63
tusharkashyap63

Reputation: 11

Use:

function rotate(arr){
    let toBeLast = arr[0];
    arr.splice(0, 1);
    arr.push(toBeLast);
    return arr;
}
console.log(rotate(['a', 'b', 'c']));

Upvotes: 0

index
index

Reputation: 41

arr.unshift(...arr.splice(arr.indexOf(k)))

Using unshift(), splice() and indexOf(), this is a one line that should help. arr is the array you want to rotate and k the item you want as first element of the array. An example of function could be:

let rotate = function(k, arr) {
    arr.unshift(...arr.splice(arr.indexOf(k)))
}

And this are examples of usage:

let array = ['a', 'b', 'c', 'd']
let item = 'c'

rotate(item, array)
console.log(array)

// > Array ["c", "d", "a", "b"]

Finally back to the original array:

rotate('a', array)
console.log(array)

// > Array ["a", "b", "c", "d"]

Upvotes: 1

Nithish
Nithish

Reputation: 5999

Here I have created a utility where, the input array will not get mutated even after rotating the array as per the requirement.

function rotate(a){
  let inputCopy = [...a]
  let myShift = inputCopy.shift();
  let myFinalS = [...inputCopy, myShift]
  return myFinalS
}

console.log(rotate([1,2,3]))
console.log(rotate(["a","b","c"]))

Hope this helps.

Upvotes: 1

ROOT
ROOT

Reputation: 11622

To achieve the output you are looking for, first you have to use Array.shift() to remove the first element, then using Array.push() add the element back to the end of the Array, then return the array, the issue is that you used the wrong oder for these steps, also .push() method takes element to be added as argument, here is a working snippet:

function rotate(a){
  let myShift = a.shift();
  a.push(myShift);
  return a;
}

console.log(rotate(['a', 'b', 'c']));

Upvotes: 1

Zohaib Sohail
Zohaib Sohail

Reputation: 310

function rotate(array){
   let firstElement = array.shift();
   array.push(firstElement);
   return array;
}

Upvotes: 3

Related Questions