2

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.

2
  • Also, are you choosing the 5th (index 4) spot in the array because your starting Number is 5 or because it is the spot where 5 happens to be? Put another way, what should this method do with a startNumber of 5 and an input [1,2,5,3,4,6,7,8,9]? Commented Nov 27, 2016 at 13:12
  • 1
    What have you read and what seems to be the trouble? Commented Nov 27, 2016 at 15:54

2 Answers 2

1

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];
Sign up to request clarification or add additional context in comments.

Comments

0

So I am not sure this is what you have in mind, but assuming you mean we are starting at 5 because its value (not position if you start counting at 1) is 5, the following should work (though maybe not the newfangled idea you wanted).

var startArr =[1,2,3,4,5,6,7,8,9];
var startIndex=startArr.indexOf(5);//finds 5, if you meant just because it is the 5th. say startArr=5-1
if (startIndex!=-1){
    var a1=startArr.slice(startIndex);
    var a3=a1.concat(startArr.slice(0,startIndex));
    //a3 now contains what you wished for, you may console.log(a3) to see
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.