Reputation: 27
I am doing dragndropping and I need to swap the elements when swaping, there is an array of objects and the index of the active object and the one that is swapped, how can I swap them in js without mutating the original object
let allData = [{name:1},{name:2},{name:3}]
I need get after swapping
[{name:2},{name:1},{name:3}]
example what i need to do
case CHANGE_TAB_ORDER:
const {activeElementIndex} = action.payload;
const {swapedElementIndex} = action.payload
return {
...state,
stages: ? here i need to swap objects in array with activeElementIndex and swapedElementIndex
}
stages is array of objects
Upvotes: 0
Views: 651
Reputation: 253
If you want to make operations in the array without mutating the original object you should make a copy first, and then you only need a temp variable to swap the items, returning the new array.
const array = [{name: 1}, {name: 2}, {name: 3}]; // Originalarray
const arrayCopy = array.slice(); // Clone the array
function swapItems(pos1, pos2, nextArray) {
const temp = nextArray[pos1]; // Temp variable
nextArray[pos1] = nextArray[pos2]; // Swap the items
nextArray[pos2] = temp;
return nextArray; // Return the array
}
const swappedArray = swapItems(0, 1, arrayCopy);
console.log(swappedArray); // Print the array :)
Upvotes: 2
Reputation: 3032
without mutating you mean create a copy? Then like this.
const {activeElementIndex, swapedElementIndex} = action.payload
return {
...state,
stages: (stages => {
[stages[activeElementIndex], stages[swapedElementIndex]] =
[stages[swapedElementIndex], stages[activeElementIndex]];
return stages })([...state.stages])
}
(If you want to save an old then just replace [...state.stages] in my code with state.stages)
Upvotes: 0