title: How do I swap array elements in an immutable fashion within a Redux reducer?
body: <p>The relevant Redux state consists of an array of objects representing layers. </p>
  
  <p><em>Example:</em></p>
  
  <pre><code>let state = [
      { id: 1 }, { id: 2 }, { id: 3 }
  ]
  </code></pre>
  
  <p>I have a Redux action called moveLayerIndex:</p>
  
  <p><strong>actions.js</strong></p>
  
  <pre><code>export const moveLayerIndex = (id, destinationIndex) =&gt; ({
      type: MOVE_LAYER_INDEX,
      id,
      destinationIndex
  })
  </code></pre>
  
  <p>I would like the reducer to handle the action by swapping the position of the elements in the array.</p>
  
  <p><strong>reducers/layers.js</strong></p>
  
  <pre><code>const layers = (state=[], action) =&gt; {
      switch(action.type) {
          case 'MOVE_LAYER_INDEX':
  </code></pre>
  
  <p>/* What should I put here to make the below test pass */</p>
  
  <pre><code>        default:
           return state
      }
  }
  </code></pre>
  
  <p>The test verifies that a the Redux reducer swaps an array's elements in immutable fashion.</p>
  
  <p>Deep-freeze is used to check the initial state is not mutated in any way.</p>
  
  <p><strong>How do I make this test pass?</strong> </p>
  
  <p><strong>test/reducers/index.js</strong></p>
  
  <pre><code>import { expect } from 'chai'
  import deepFreeze from'deep-freeze'
  
  const id=1
  const destinationIndex=1
  
   it('move position of layer', () =&gt; {
      const action = actions.moveLayerIndex(id, destinationIndex)
      const initialState = [
          {
            id: 1
          },
          {
            id: 2
          },
          {
            id: 3
          }
      ]
      const expectedState = [
          {
            id: 2
          },
          {
            id: 1
          },
          {
            id: 3
          }
      ]
      deepFreeze(initialState)
      expect(layers(initialState, action)).to.eql(expectedState)
   })
  </code></pre>