0

Is it possible to make a multidimensional array in javascript?

It should look like this:

$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

But I need to use $cars.push(); to first add all data for the first rows (the cars). Then the data "22", "15", "5" and "17". Then "18", "13", "2" and "15".

Then it should be printed in the same order as the original array (table-view).

EDIT LIKE this:

var cars = [];

cars.push("Volvo", "BMW", "Saab", "Land Rover");
cars.push(22, 15, 5, 17);
cars.push(18, 13, 2, 15);

and print it like this to html

Volvo, 22, 18

BMW, 15 13

Saab, 5, 2

Land Rover, 17, 15

Stefan
  • 11
  • 1

3 Answers3

0

You could refer the documentation.

As @sampson suggested in the comment above in your case it is,

 var cars = [ 
              [ "Volve", 22, 18 ], 
              [ "BMW", 15, 13 ],
              [ "Saab", 5, 2],
              [ "Land Rover", 17, 15]
            ];
hkasera
  • 2,118
  • 3
  • 23
  • 32
0

You can rebuild the array with the change of position i and j. And you can switch it from one appearance to the other one.

function transpose(source, target) {
    source.forEach(function (a, i) {
        a.forEach(function (b, j) {
            target[j] = target[j] || []
            target[j][i] = b;
        });
    });
}

var cars = [["Volvo", 22, 18], ["BMW", 15, 13], ["Saab", 5, 2], ["Land Rover", 17, 15]],
    pCars = [];

transpose(cars, pCars);
document.write('<pre>' + JSON.stringify(pCars, 0, 4) + '</pre>');
cars = [];
transpose(pCars, cars);
document.write('<pre>' + JSON.stringify(cars, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • What if my array look like this. var cars = [ ["Volvo", "BMW", "Saab", "Land Rover"], [22, 15, 5, 17], [18, 13, 2, 15] ]; – Stefan Dec 12 '15 at 09:25
  • I supposed you're looking for the word "transpose" rather than "transform". –  Dec 12 '15 at 10:59
0

Is it possible to make a multidimensional array in javascript?

Yes, it is.

But that doesn't seem to be your question. Rather, your question seems to be, if I have an array of arrays, where the first subarray contains values for field 1, the second subarray contains values for field 2, and so on, then how do I re-organize this into in array of arrays where each subarray contains all fields for one object.

As another responder mentioned, this is array transposition. A simple way is:

function transpose(a) {
  return a[0] . map((col, i) => a . map(row => row[i]));
}

Use this as:

var cars = [];

cars.push(["Volvo", "BMW", "Saab", "Land Rover"]);
cars.push([22, 15, 5, 17]);
cars.push([18, 13, 2, 15]);

console.log(transpose(cars));
  • Is it then possible to loop through the array like variables: cars[0] (volvo) cars[1] (22) cars[2] (18) – Stefan Dec 13 '15 at 09:50
  • Suggest reading up on the basics of JS arrays and loops. Also run the code above and examine the internal structure of `transpose(cars)`. –  Dec 13 '15 at 13:53