0

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

alex
  • 27
  • 5
  • 1
    https://stackoverflow.com/questions/872310/javascript-swap-array-elements – wangdev87 Nov 17 '20 at 17:57
  • Does this answer your question? [Swap two array elements in a functional way](https://stackoverflow.com/questions/42258865/swap-two-array-elements-in-a-functional-way) – Heretic Monkey Nov 17 '20 at 18:03
  • yes but how can I swap them correct way in reducer, I update my question – alex Nov 17 '20 at 18:18
  • What was confusing in the answers? Some of them provide functions that take an array and two indexes and return the mutated array... – Heretic Monkey Nov 17 '20 at 18:25

2 Answers2

2

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 :)
Roberto
  • 253
  • 1
  • 9
0

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)

Dmitry Reutov
  • 2,995
  • 1
  • 5
  • 20