I am looking to select an element from an array, relocate it to a different index, and then shift the elements in-between by 1 position. Consider this as drag-and-drop functionality, where if the starting index (from) is less than the destination index (to), then I want the shift to be towards the left; otherwise, it should be towards the right. Input:
let data = [ 0, 1, 2, 3, 4, 5, 6 ]
Task1:
insertAndShift(data, 0, 3): Select the element at index 0, shift indexes 1, 2, 3 to the left, and then insert the index 0 at position 3.
Expected Output:
[ 1, 2, 3, 0, 4, 5, 6 ]
Task2:
insertAndShift(data, 3, 0): Take the element at index 3, shift indexes 0, 1, 2 to the right, and then insert the element at index 3 into position 0.
Expected Output:
[ 0, 1, 2, 3, 4, 5, 6 ]
I attempted this methodology:
Referencing Rotating an array in place, although the code seemed flawed (temp variable undefined + incomplete result + potential functioning only for Right shifts):
insertAndShift(data, from, to)
{
if(from < to)
{
// rotate in between - LEFT
}
else
{
// swap elements
let temp = data[from];
data[from] = data[to];
data[to] = temp;
// rotate in between - RIGHT
let newData = this.rotate(data.slice(to, from - 1), 1)
let result = [];
result.push(data.slice(0,1));
newData.map((element) => result.push(element))
for(let i = from+1; i < data.length; i++)
{
result.push(data[i]);
}
this.setState({data: result})
}
}
rotate(arr, k) {
var l = arr.length;
arr = this.reverseArr(arr, 0, l - 1);
arr = this.reverseArr(arr, 0, k - 1);
arr = this.reverseArr(arr, k, l - 1);
return arr;
}
reverseArr(arr, left, right) {
while (left < right) {
var temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return arr;
}
Similarly, referring to Javascript (dynamic) insert into array, then shift all elements underneath +1, which seems to output just one item:
else
{
let result = data.splice(to, 1, data[from]);
this.setState({allTasksArray: result})
}
What would be the proper approach to achieve both Left and Right shifts?