Reputation: 130
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?
Upvotes: 2
Views: 260
Reputation: 130
Combining knowledge from Harish' answer I refactored the algorithm. Now it works with both examples, where arrays can look like this.
const array1 = [1, 2, 3, 4, 5]
const array2 = [4, 5, 1, 2, 3]
So here goes the function
const sortedArray = (pos) => {
// First of all - sort the array
const newArr = arr.sort((a, b) => a - b);
// and then splice it and add this part to the start of the array
newArr.unshift(...newArr.splice(pos-1));
return newArr;
}
Upvotes: 1
Reputation: 1911
You can do like, remove the elements from your index
to length
of the array and push it to start of the same array
const array = [1, 2, 3, 4, 5];
const index = 2;
array.unshift(...array.splice(index))
console.log(array)
Upvotes: 4
Reputation: 35263
You could get the index of the current dot value. Then create an array with 2 iterations of the original array using [...array, ...array]
. For the given array, it will look like [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
. Then use slice
to get array.length
items starting from index
function getRotation(array, value) {
const index = array.indexOf(value);
return [...array, ...array].slice(index, index + array.length)
}
console.log(getRotation([1, 2, 3, 4, 5], 3))
console.log(getRotation([1, 2, 3, 4, 5], 5))
Upvotes: 1