Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
Rotate the array by d elements in JavaScript

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!