0

I have an array which contains numeric values, these values range from 0 to 6. I would like to sort them in an "ascending" order, by specifying the starting number and ending number.

So let's say I want to start from 2, and end on 1..

These values would have to be sorted as such: 2, 3, 4, 5, 6, 0, 1

Or if I want them to start from 4, and end on 3..

These values would have to be sorted as such: 4, 5, 6, 0, 1, 2, 3

I may be overthinking this, but I'm not sure how to use the .sort() functionality for that, how and what would I have to compare against which values exactly?

const startFrom = 4;
const endAt = 3;
const arr = [0, 1, 2, 3, 4, 5, 6];

arr.sort((a, b) => {
  // What should I compare to what here?
  // .. and what do I return in which case?
});
Martin K
  • 21
  • 3

1 Answers1

0

Using sort,splice,push and unshift

const startFrom = 4;
const endAt = 3;
const arr = [0, 1, 2, 3, 4, 5, 6];
arr.sort(function(a,b){return a-b});
arr.splice(arr.indexOf(startFrom),1)
arr.splice(arr.indexOf(endAt),1)
arr.unshift(startFrom)
arr.push(endAt)
console.log(arr)
ellipsis
  • 12,049
  • 2
  • 17
  • 33