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

4
  • 1
    stackoverflow.com/questions/872310/… Commented Nov 17, 2020 at 17:57
  • Does this answer your question? Swap two array elements in a functional way Commented Nov 17, 2020 at 18:03
  • yes but how can I swap them correct way in reducer, I update my question Commented Nov 17, 2020 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... Commented Nov 17, 2020 at 18:25

2 Answers 2

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

swappedArray print an object, not an array.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.