Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap two elements inside of a 2D Array in JavaScript? (Confused about what I’m seeing from console.log in Chrome)

I want to swap two arrays inside a 2D array, however JS seems to be doing that before my actual swap is happening.

This is for an algorithm I'm working on, providing each possible way to display a list of points. I have tried several ways of doing this, but the key problem keeps returning, and I've managed to crop it down to this peace of code:

var points = [[1,2],[10,20],[100,200]];
console.log(points);
var a = points[1][0];
var b = points[1][1];
points[1][0] = points[2][0];
points[1][1] = points[2][1];
points[2][0] = a;
points[2][1] = b;
console.log(points);

I know this code isn't close to being DRY, but it has the same problem: 'points' is logged to the console in the line after being declared, though in that log, it is already swapped? How is that possible, as there were no commands yet saying it to do so. How does JavaScript handle this peace of code? And why doesn't mine seem to be working?

**The expected output for the first log is: [[1,2],[10,20],[100,200]] **and for the second log: [[1,2],[100,200],[10,20]]

The StackOverFlow snipped runs it as it is expected, but Chrome runs it differently

like image 683
Stijn van Balen Avatar asked Jan 27 '23 17:01

Stijn van Balen


1 Answers

I believe what's happening here is that the console is showing something like this (in Firefox):

initial console

But then you click to expand it to take a look inside the array, the items are swapped:

expanded console

This is because the console is actually showing you a reference to the array, and since your algorithm modifies the original array in place, by the time you click to expand the element in console, the reference has been modified. Your code is fine, you might try using .toString() or JSON.stringify or even [...points] to make sure what's output to the console in each line are different values and not a reference to the same value.

Running your exact algorithm with console.log(points.toString()) instead, I see this (again in Firefox):

toString demo

And just for demonstration purposes, here's how you can simplify your code to do the same thing using destructured assignment:

var points = [[1, 2], [10, 20], [100, 200]];
console.log(points.toString());
[points[1], points[2]] = [points[2], points[1]];
console.log(points.toString());
like image 58
p.s.w.g Avatar answered Jan 29 '23 06:01

p.s.w.g