Code Lab

Swap two array elements

EasyBasics5 min

Write a function swapItems(items, i, j) that swaps two elements of the array items: the element at index i and the element at index j.

  • Change items itself and return that same array, not a new one. The other elements stay where they are.
  • Indexes start at 0. i and j are always valid indexes of items. They can be equal (then nothing changes), and i can be greater than j.
  • Elements can be numbers or strings (the number 7 and the string '7' are different values). The same value can appear more than once: swap by position, not by value.
  • You may use a helper variable.

Examples

swapItems(['a', 'b', 'c'], 0, 2)

Returns [ 'c', 'b', 'a' ]

swapItems([1, 2, 3, 4], 1, 2)

Returns [ 1, 3, 2, 4 ]

swapItems([5, 6, 7], 1, 1)

Returns [ 5, 6, 7 ]

Source

Loading the editor...
  1. InputswapItems([ 'a', 'b', 'c' ], 0, 2)
    Expected[ 'c', 'b', 'a' ]
  2. InputswapItems([ 1, 2, 3, 4 ], 1, 2)
    Expected[ 1, 3, 2, 4 ]
  3. InputswapItems([ 5, 6, 7 ], 1, 1)
    Expected[ 5, 6, 7 ]
  4. Returns the same array, now changed

Hidden tests run on Submit.