albert105 albert105 - 13 days ago 5
Javascript Question

Rearrange array in Javascript with ES6

I want to reorder an Array with ES6.
For example:

[1,2,3,4,5,6,7,8,9]


When my starting number is 5, I want a new array like this:

[5,6,7,8,9,1,2,3,4].


I am able to fix this by looping, comparing, slicing, glueing the thing back together.

However I've read some interesting array functionality with ES6 that might make this easier. But I'm having trouble putting this into practise.

Answer

It can be

let newArr = [...arr.slice(arr.indexOf(5)), ...arr.slice(0, arr.indexOf(5))]

or

let newArr = [...arr];
newArr = [...newArr.splice(arr.indexOf(5)), ...newArr];