0

I have written a code for rotating a 1-D array by d elements but I just wondering if there is any shorter way to write this code? for instance:

arr = [1,2,3,4,5,6,7] , d = 3
newArr = [4,5,6,7,1,2,3]
const arrayRotation=(arr,d)=>{
    var k = arr.slice(d) 
    var m = new Set(k)
    var diff = ([...arr].filter(x=>!m.has(x)))
    return k.concat(diff)
}

I had to use Set so I can filter the difference between 2 arrays. Is there any better way ( complexity wise) to solve this problem?

saran
  • 356
  • 1
  • 3
  • 14
  • 1
    `const newArr = [...arr.slice(d % arr.length), ...arr.slice(0, d % arr.length)]` – jabaa Jan 30 '22 at 23:46
  • 2
    Duplicate: [Rotate the elements in an array in JavaScript](https://stackoverflow.com/questions/1985260/rotate-the-elements-in-an-array-in-javascript) –  Jan 30 '22 at 23:49
  • Please always search for existing questions first. –  Jan 30 '22 at 23:50

2 Answers2

1

You can use slice twice and concatenate the subarrays:

const arr = [1,2,3,4,5,6,7], d = 3;
const newArr = [...arr.slice(d % arr.length), ...arr.slice(0, d % arr.length)];

console.log(newArr);
jabaa
  • 5,844
  • 3
  • 9
  • 30
1

Assuming D is positive you can just use the index to map old idx => new idx.

const arr = [1,2,3,4,5,6,7]
const rot = 3;
const newArr = arr.map((el, idx) => arr[(idx+rot)%arr.length])
console.info(newArr);
>>> [4,5,6,7,1,2,3]
nlta
  • 1,716
  • 1
  • 7
  • 17