SteveD
SteveD

Reputation: 13

Adding a new entry to a multidimensional javascript array

All the examples that I have seen on this site suggest that I should be able to do this:

var multiArray = []
var singleArray = []

singleArray[0] = "10"
singleArray[1] = "11"

multiArray.push(singleArray)

singleArray[0] = "20"
singleArray[1] = "21"

multiArray.push(singleArray)

and I would expect multiArray to contain:

["10", "11"]["20", "21"}

In fact it contains:

["20", "21"]["20", "21"}

It looks as though multiArray holds a reference to singleArray rather than the data. So changing the contents of singleArray affects both entries in multiArray.

Have I made a very basic error or is there some workaround for this?

Thanks for any help.

Upvotes: 1

Views: 111

Answers (3)

Vivin Paliath
Vivin Paliath

Reputation: 95528

You're not pushing in a copy of the array. You're pushing in a copy of the reference to the array. Since the copies all point to the same array, you are seeing it twice.

You can simply do this:

multiArray.push([10,11], [20,21])

Another way is to do this:

multiArray.push(JSON.parse(JSON.stringify(singleArray)));

Here you're stringifying the array and then parsing it again, in effect creating a new array. A kind of "cloning", if you will.

Using slice is a better alternative for this particular scenario:

multiArray.push(singleArray.slice(0));

Upvotes: 1

talemyn
talemyn

Reputation: 7950

Lots of ways to do this and get what you want . . . the other two answers will do it, as will these two approaches:

multiArray.push(["10", "11"]);
multiArray.push(["20", "21"]);

. . . and . . .

multiArray.push(new Array("10", "11"));
multiArray.push(new Array("20", "21"));

Both result in an array of: [["10", "11"], ["20", "21"]]

In the end, the important thing is that you need to create a new array instance for each set of values that you store, since the outer array will just be storing pointers to each inner array that it contains.

Upvotes: 1

Andrew Templeton
Andrew Templeton

Reputation: 1696

It's an object reference problem - Arrays are objects, so when you modify [0] and [1], you're modifying it in both places. Use a slice to copy the contents:

var multiArray = [],
  singleArray = [];

singleArray[0] = "10";
singleArray[1] = "11";

multiArray.push(singleArray.slice(0));

singleArray[0] = "20";
singleArray[1] = "21";

multiArray.push(singleArray);

console.log(multiArray); // [["10", "11"], ["20", "21"]]

Upvotes: 0

Related Questions