How does changing the position of the element in the array?

Need to write a function that receives as argument the array and change a zero and the last element of the array places. I found this solution, but understand it does not work. Please explain.

function swap(arr, from, to) {
 arr.splice(from, 1, arr.splice(to, 1, arr[from])[0]);
}

var letters = ["a", "b", "c", "d", "e", "f"];

swap(letters, 0, 5);

console.log(letters);
April 3rd 20 at 17:35
2 answers
April 3rd 20 at 17:37
Solution
To swap, you should:
  1. to pull first
  2. pull the second,
  3. paste to a new location first
  4. paste to a new location the second.

Method array .splice() is able to rip and insert at the same time. His arguments:
position-of-which, how-yank, insert-this, paste-still, ...
And it returns an array of tear. So [0] will return the first tear item.

You can decorate your function read more:
function swap(arr, from, to) {
 // pull out:
 const A = arr.splice(from, 1)[0];
 const B = arr.splice(to-1, 1)[0]; 
 // -1 because the array is shorter after the first operation

 // insert
 arr.splice(from, 0, B); // 0 - nothing cut out, just insert
 arr.splice(to, 0, A);
}

Even easier looks the same without any splice()
function swap(arr, from, to) {
 // yank-copy:
 const A = arr[from];
 const B = arr[to]; 

 // plug-in-model
 arr[from] = B;
 arr[to] = A;
}
Thank you very much! But there is an additional question.

arr - the array.
from - the index of the first element to change position.
to - the index of the second element to change the position.

Right you know? - Angelina.Purdy commented on April 3rd 20 at 17:40
@Angelina.Purdy, right - fabiola_Hoeger commented on April 3rd 20 at 17:43
It seems that found

function swap(arra) {
 [arra[0], arra[arra.length - 1]] = [arra[arra.length - 1], arra[0]];
 return arra;
}
- Angelina.Purdy commented on April 3rd 20 at 17:46
April 3rd 20 at 17:39
Here is the documentation on MDN

Find more questions by tags JavaScript