3

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.

Yuriy Yakym
  • 3,616
  • 17
  • 30

2 Answers2

1

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
Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
0

This is kind of a dirty fix, but I'll give it anyway:

var panel = new Array(3).fill(new Array(3).fill('*'));
panel[1] = [panel[1][0],"#",panel[1][2]];
console.log(panel);

/*
Result:
[
    ['*', '*', '*'],
    ['*', '#', '*'],
    ['*', '*', '*']
]
*/