Rotate the elements in an array in JavaScript

后端 未结 30 1205
走了就别回头了
走了就别回头了 2020-11-22 10:55

I was wondering what was the most efficient way to rotate a JavaScript array.

I came up with this solution, where a positive n rotates the array to the

30条回答
  •  孤街浪徒
    2020-11-22 11:02

    I am not sure if this is the most efficient way but I like the way it reads, it's fast enough for most large tasks as I have tested it on production...

    function shiftRight(array) {
      return array.map((_element, index) => {
        if (index === 0) {
          return array[array.length - 1]
        } else return array[index - 1]
      })
    }
    
    function test() {
      var input = [{
        name: ''
      }, 10, 'left-side'];
      var expected = ['left-side', {
        name: ''
      }, 10]
      var actual = shiftRight(input)
    
      console.log(expected)
      console.log(actual)
    
    }
    
    test()

提交回复
热议问题