Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rearrange item of an array to new position in Swift?

Tags:

arrays

swift

Consider the array [1,2,3,4]. How can I rearrange the array item to new position.

For example:

put 3 into position 4 [1,2,4,3]

put 4 in to position 1 [4,1,2,3]

put 2 into position 3 [1,3,2,4].

like image 689
Morty Choi Avatar asked Apr 11 '16 06:04

Morty Choi


People also ask

How do you change the position of an item in an array?

To change the position of an element in an array:Use the splice() method to insert the element at the new index in the array. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.

How do you move an element from an array to first position?

To move element to first position in array with JavaScript, we can use the spread operator and the array slice method. We call data. slice to get the last element and the first 3 elements respectively. Then we spread each array into a new array to populate the values of the returned arrays in the new array.

How do you swap an element in an array in Swift?

How to swap two items in an array using swapAt() If you need to have two items in an array change places, the swapAt() method is exactly what you want: provide it two indexes inside your array, and the items at those positions will be swapped.


1 Answers

Swift 3.0+:

let element = arr.remove(at: 3) arr.insert(element, at: 2) 

and in function form:

func rearrange<T>(array: Array<T>, fromIndex: Int, toIndex: Int) -> Array<T>{     var arr = array     let element = arr.remove(at: fromIndex)     arr.insert(element, at: toIndex)      return arr } 

Swift 2.0:

This puts 3 into position 4.

let element = arr.removeAtIndex(3) arr.insert(element, atIndex: 2) 

You can even make a general function:

func rearrange<T>(array: Array<T>, fromIndex: Int, toIndex: Int) -> Array<T>{     var arr = array     let element = arr.removeAtIndex(fromIndex)     arr.insert(element, atIndex: toIndex)      return arr } 

The var arr is needed here, because you can't mutate the input parameter without specifying it to be in-out. In our case however we get a pure functions with no side effects, which is a lot easier to reason with, in my opinion. You could then call it like this:

let arr = [1,2,3,4] rearrange(arr, fromIndex: 2, toIndex: 0) //[3,1,2,4] 
like image 68
Luka Jacobowitz Avatar answered Sep 20 '22 01:09

Luka Jacobowitz