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
itemsitself and return that same array, not a new one. The other elements stay where they are. - Indexes start at
0.iandjare always valid indexes ofitems. They can be equal (then nothing changes), andican be greater thanj. - Elements can be numbers or strings (the number
7and 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 ]
Loading the editor...
- Input
swapItems([ 'a', 'b', 'c' ], 0, 2)Expected[ 'c', 'b', 'a' ] - Input
swapItems([ 1, 2, 3, 4 ], 1, 2)Expected[ 1, 3, 2, 4 ] - Input
swapItems([ 5, 6, 7 ], 1, 1)Expected[ 5, 6, 7 ] - Returns the same array, now changed
Hidden tests run on Submit