How do I swap array elements?

let arr = ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб']

What is the easiest way to add the 0 element 'вс' to the end of the array?

I got it like this:

let shiftElem = arr.shift()
arr.push(shiftElem)

Is it possible to make it easier?

Author: UModeL, 2020-11-30

3 answers

The most obvious and simple option:

let arr = ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб'];
console.log(arr.concat(arr.splice(0,1)));
 4
Author: UModeL, 2020-11-30 19:31:02

In terms of code simplicity, it's easier to write this in one command.:

let arr = ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб']

arr.push(arr.shift())

console.log(arr)

The performance should be pretty good too. The only case where this might be worse than a manual loop is if memory is reallocated when deleting an item, but this situation is quite unlikely.

PS: Well, do not forget that the asymptotics of this code is still linear.

 4
Author: Qwertiy, 2020-11-30 21:30:43

If you really want to be guaranteed without allocating memory, then you can do this (although I would not do it without profiling data):

let arr = ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб']

let x = arr[0]
arr.copyWithin(0, 1)
arr[arr.length - 1] = x

console.log(arr)
 1
Author: Qwertiy, 2020-11-30 21:30:28