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]
.
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.
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 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.
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 }
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With