1

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?

5
  • 2
    Try changing mapLocs[i] = new Array(myLocs); to mapLocs[i] = myLocs; Commented Aug 1, 2016 at 14:47
  • You can also try mapLocs[i] = [myPhotogs[i].phtName,myPhotogs[i].phtLoc,x+1] Commented Aug 1, 2016 at 14:49
  • Ah! Brilliant, that works a treat! Thank you so much! Commented Aug 1, 2016 at 14:49
  • Your code never declares mapLocs. Prior to the for loop, you need something like: var mapLocs = [];. In what you have provided, you also have an extra } which, in addition, does not match your indenting. Commented Aug 1, 2016 at 14:53
  • This was just a snippet of the code which I cut and pasted. mapLocs is actually declared elsewhere, and the extra } was copied in error. Commented Aug 1, 2016 at 15:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I've accepted this as correct because it is correct (I tried it out), though I've actually gone with the suggestion in the first comment under my original post.
Thanks anyways! Glad you found your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.