Let's assume I have a simple array
const simpleArray = [1, 2, 3, 4, 5];
In case of, for example, I want to create a carousel and connect dots to click events in Vue or React. So clicking on a dot I want to sort my array so first slide will be the slide with the index of the dot. Hence if the index of the dot is 3 - my array should look like this now
const updatedSimpleArray = [3, 4, 5, 1, 2];
With this idea in mind I came to conclusion of creating this method.
const sortedArray = (pos) => {
// pos is the dot index of the dot
// if index is 1 - simply sort the array
if ( pos == 1 ) return arr.sort();
// otherwise - create two separate arrays and concat them
const firstArr = arr.filter(el => el >= pos);
const secondArr = arr.filter(el => el < pos);
const newArr = [...firstArr, ...secondArr];
return newArr;
}
What do you think about my approach and time/memory complexity? Would you use another approach?
EDIT
There is a problem if my array is not sorted. If it looks like this
const array = [4, 5, 1, 2, 3]
Whole function is not working correctly. My thoughts - sort it first and then filter/splice on given index?