I have an array and I want to swap two elements in the array. If the array is non-empty, I can simply do:
const swap = (arr, a, b) => {
const temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
}
and the function can correctly swap the value of the index a
and b
in the array arr
.
However, if the array has some empty elements, such as [1, , , ,]
, and the result of the swap
will be [undefined, empty, 1, empty]
, while the expected result should be [empty × 2, 1, empty]
. So how do I modify the swap
function so that the result will be correct. Or is there any way to make a specific index to be empty in an array?
Also failed:
const swap = (arr, a, b) => {
const temp = arr[a]
arr.splice(a, 1, arr[b])
arr.splice(b, 1, temp)
}
Original Problem:
I have an array let arr = [1, , , ,]
(which will show [1, empty × 3]
in console) with length 4, and I want to move the first element to the third, that is: [empty × 2, 1, empty]
. How do I achieve that?
I have tried splice
and directly assign value to the array but they won't work.
You do need splice - combined with shift to get the first item
let arr = [1, , , ,]
console.log(arr)
arr.splice(2, 0, arr.shift());
console.log(arr)