4

Maybe I have just been searching on the wrong keywords, but I have been trying to find an example of a JavaScript (preferably ES2015+) function to swap two array values in a non-mutating (immutable) way. I'd also like to do this using pure JS and not have to add in a immutability library.

For example, if I have [1, 2, 3, 4, 5, 6], I'd like to pass 3 and 4 (or probably their indexes) into a function that returns a new array [1, 2, 4, 3, 5, 6]. I found a few ways to do this, but they mutate the array by directly replacing the values. I need an immutable way. I am guessing maybe using slice? I am doing this is a React component if that matters and the array is a state value.

TIA!

2
  • 1
    Just clone the array (using slice) and then swap them.
    – Bergi
    Apr 5, 2016 at 13:27
  • @JaredSmith: That seems to miss the elements between firstIndex and secondIndex, and it also drops the last element.
    – Bergi
    Apr 5, 2016 at 13:28

2 Answers 2

6

Not ES6 (Still learning it)

function swap(array, first, second){
  var final = array.slice();
  temp = final[first];
  final[first] = final[second];
  final[second] = temp;
  return final
}

ES6 Thanks to @Benjamin

const swapIndices = (array,index1,index2) => { 
  const newArray = array.slice(); 
  newArray[index1] = array[index2]; 
  newArray[index2] = array[index1]; 
  return newArray; 
}

1
  • 1
    const swapIndices = (array,index1,index2) => { const newArray = array.slice(); newArray[index1] = array[index2]; newArray[index2] = array[index1]; return newArray; } swapIndices(array,2,3) => [1, 2, 4, 3, 5, 6] I guess I would do it like this? but with line breaks :P
    – Benjamin
    Apr 5, 2016 at 13:56
1
function swap(arr, i1, i2) {
    // i1 must be lower
    if (i1 > i2) i1 = [i2, i2 = i1][0];
    return arr
        .slice(0,i1)
        .concat(arr[i2])
        .concat(arr.slice(i1+1,i2))
        .concat(arr[i1])
        .concat(arr.slice(i2+1))
}

Maybe not perfect, but a stepping stone :)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.