Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two-dimensional string array creation [duplicate]

I'm trying to create two-dimensional array of 1-character strings in javascript this way:

var panel = new Array(3).fill(new Array(3).fill('*'));

Result is

[
    ['*', '*', '*'],
    ['*', '*', '*'],
    ['*', '*', '*']
]

After that I need to replace middle string:

panel[1][1] = '#';

And the result is

[
    ['*', '#', '*'],
    ['*', '#', '*'],
    ['*', '#', '*']
]

So it seems that prototype fill function fills array with object by reference.

Is it possible to force fill function to fill array with different object instances? If no, what approach of creation this-like two-dimensional array in your opinion is the best?


Update

Algorithm assumes to create a plane of asterisks, and then a lot of those asterisks will be replaced with another symbols creating some reasonable result. After that it will be printed.

In C it could be done using matrix of chars and changing symbols at any indices. But as far as we cannot simply change single symbol in javascript string, I'm trying to find some good analogue.

Currently I've created two-dimensional array using two loops, then changing symbols I need, and after that with map and join functions I'm joining this result to a single string. But is it the best solution?

Thank you.

like image 624
Yuriy Yakym Avatar asked Feb 28 '26 08:02

Yuriy Yakym


1 Answers

Not sure about the efficiency of this method but Converting the array into string using JSON.stingify() and then parsing back to original format by JSON.parse() makes the objects loose its original reference and work without any pain.

var panel = new Array(3).fill(new Array(3).fill('*'));
var copy = JSON.parse(JSON.stringify(panel));

copy[1][1] = '#';

//you can assign the value of variable 'copy' back to 'panel' if required.

document.write(JSON.stringify(copy)); //for demo

You can simplify the above logic into single liner of code without extra variable, this way

var panel = JSON.parse(JSON.stringify(new Array(3).fill(new Array(3).fill('*'))));
panel[1][1] = '#';

document.write(JSON.stringify(panel)); //for demo
like image 131
Rajshekar Reddy Avatar answered Mar 02 '26 22:03

Rajshekar Reddy



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!