Drum
Drum

Reputation: 507

Building a 2D Array in Javascript

I've been trying to build a 2D array in javascript, but not having much success. I'm pulling some data from a DB and I then want to combine some fields into a 2D array in order to use it elsewhere in the code. Ideally what I want to end up with is:

mapLocs = [
    ['name a','location a',1],
    ['name b','location b',2],
    ['name c','location c',3]
]

here is the code I am using to build the mapLocs array:

    for(i = 0;i < phtLen;i++){
        var x = i + 1;
        var myLocs = new Array(myPhotogs[i].phtName,myPhotogs[i].phtLoc,x);
        console.log(myLocs);
        mapLocs[i] = new Array(myLocs);
        }
    }

which is pretty much the method that I've gathered from reading similar problems here. The console.log() outputs an array consisting of the three elements I want, but if I try to access mapLocs it doesn't seem to consist of three arrays as I would have expected, but of three elements each of which is made up of the three elements in the myLoc array if that makes sense? So:

console.log(mapLocs[0][0]); // Joe Bloggs, SW1A 1AA, 1

where I was expecting just 'Joe Bloggs' and

console.logs(mapLocs[0][1]); // undefined

What am I doing wrong?

Upvotes: 1

Views: 72

Answers (1)

ingleback
ingleback

Reputation: 316

The explicit new Array() constructor does not take an array and make a new array identical to the argument array, but takes a list of arguments that you wish to be contained within the new array. So in the line

mapLocs[i] = new Array(myLocs)

mapLocs[i] is actually being set to

[[Joe Bloggs, SW1A 1AA, 1]]

Instead, you could say

mapLocs[i] = myLocs.slice()

which will clone myLocs and place it at index i in mapLocs, resulting in the output you want.

Upvotes: 1

Related Questions