Joaquin
Joaquin

Reputation: 43

How to create nested arrays?

I've been looking all over stackoverflow for something to help me implement an AreaChart. The problem is that I have something like this.

var items = new Array();
if ($(result).find('dato').length > 0 ) {
  items = ["Date", "Kg Emitted", "Kg Reduced"];
  $(result).find('dato').each(
    function (i) {
      var item = new Array();
      var date = $(this).find("fecha").first().text();
      var kge = parseInt($(this).find("emitido").first().text());
      var kgr = parseInt($(this).find("reducido").first().text());
      item = [date,kge,kgr];
      items.push.apply(items, item)
    }
  );
};

The problem is that I need it in a format like:

items = ["Date","Kg Emitted", "Kg reduced"], [2013-01-01, 3, 4], [2013-01-02, 1, 3], etc

I would appreciate any help on how to format this nested array, because so far I've tried items.push.apply(items, item), but it doesn't seem to work.

Upvotes: 2

Views: 10749

Answers (3)

user2050393
user2050393

Reputation:

Everybody gave you the right answer here, i want to add just a little fix, the first value in your array is incorrect and is actually 3 rows.

See the difference in this fiddle

you need to add another [..] .

Upvotes: 1

Scott Mermelstein
Scott Mermelstein

Reputation: 15397

Your initialization of items isn't setting it up as a nested array. Element 0 is "Date", 1 is "Kg Emitted" and 2 is "Kg Reduced".

You want to start it with

items = [["Date", "Kg Emitted", "Kg Reduced"]];

This will instead make Element 0 of the array be ["Date", "Kg Emitted", "Kg Reduced"], which is what you say you want.

Then, as others have already said, change items.push.apply(items, item) to

items.push(item);

Upvotes: 1

Paul
Paul

Reputation: 141827

Just change items.push.apply(items, item) to items.push(item).

When you use apply like that you are effectively doing the same thing as Array.prototype.concat.

Upvotes: 1

Related Questions