2

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?

5 Answers 5

3
function rotate(array){
   let firstElement = array.shift();
   array.push(firstElement);
   return array;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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']));

1 Comment

It's working now. Thank you for the explanation as well.
1

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.

Comments

1
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"]

Comments

0

Use:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.