Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this function to swap array elements work?

I saw this function on here that will swap two array elements but I can't seem to figure out how it works. It looks like there is some sort of array destructuring going on (?). I just don't understand how and why the original data-array is actually changed.

Can someone please explain to me how this works?

const swap = (a, i, j) => {
  [a[i], a[j]] = [a[j], a[i]]  // ???
}

const data = [1, 2, 3, 4]

swap(data, 0, 2)

console.log(data)
like image 572
Đinh Carabus Avatar asked Nov 26 '25 09:11

Đinh Carabus


1 Answers

Starting with the righthand side:

[a[j], a[i]]

This creates a new array with two elements: the element at index j, followed by the element at index i.

On the left hand side it's doing destructuring

[a[i], a[j]] = 

So that's the equivalent of the following:

a[i] = theNewArray[0];
a[j] = theNewArray[1];

Since this is mutating a, those changes can be felt by any references to the array, so data will "see" the changes.

like image 142
Nicholas Tower Avatar answered Nov 27 '25 21:11

Nicholas Tower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!