North Laine
North Laine

Reputation: 404

Append an Array to an Array of Arrays in JavaScript

I started working with JavaScript last week in order to create some D3 visualizations, and have become rather stuck on what can only be a very simple task.

I have various data series for different countries, each stored in arrays, e.g.

var uk = [1,2,3,4,5,6,7,8],
    us = [8,4,7,3,7,8,3,2],
    fr = [4,6,8,3,2,6,8,4];

I want to create a master array, that contains all of these individual arrays, not concatenated/merged, so:

world = [uk, us, fr, etc]

How do I go about adding the arrays in such a manner so that they do not concatenate together? Note that there are hundreds of countries, and so I can't manually type them in, as above, and that I'm actually extracting them all from a single csv file, so can easily iterate over them as I extract them. Array.push seems to do the same as concat?

Thanks

Upvotes: 1

Views: 5813

Answers (3)

atmd
atmd

Reputation: 7490

you can add multiple arrays to another array with push

var worlds = [];
worlds.push(uk);
worlds.push(us);
worlds.push(fr);

You would of course then reference the different subsets/arrays numerically i.e. worlds[0] = the 'uk' data

You could use an object instead, that way you can access them with a string key and make the code more readable. i.e.

var worlds = {
  "uk" : uk,
  "us" : us 
};

and access the data like:

worlds.uk // will be the uk dataset/array

or

worlds["uk"] // which allows you to store "uk" as a variable

N.B. Although not the question, I see you're using D3. D3 has a json method which reads in a json file and uses that as it's data. You might be better of using a json object to hold your data and passing that stright into D3. Here's the D3 docs for .json if it helps.

It's also possible to pass a csv file to D3, which if you are not editing your data soruce might also be a solution

Upvotes: 9

WebWanderer
WebWanderer

Reputation: 10897

You could very easily add the arrays to another array like so:

var world = [
    uk, 
    us, 
    fr, 
    etc
];

Which is essentially what you have already typed up. It will most definitely work and will not concatenate them together.

Upvotes: 0

dfsq
dfsq

Reputation: 193301

Array.push seems to do the same as concat?

Not really, this is why it's different methods. What you indeed want is push. Maybe like this:

world.push(uk, us, fr);

Upvotes: 1

Related Questions