How to initialize a jagged array in JavaScript?

John Keats picture John Keats · May 9, 2011 · Viewed 15.3k times · Source

Is it possible to have a jagged array in JavaScript?

Here is the format of the data I want to store in a jagged array:

(key)(value1, value2, value3)

Can I put this in a jagged array?

Answer

Andy E picture Andy E · May 9, 2011

Yes, you can create that type of array using object or array literal grammar, or object/array methods.

An array of arrays:

// Using array literal grammar
var arr = [[value1, value2, value3], [value1, value2]]

// Creating and pushing to an array
var arr = [];
arr.push([value1, value2, value3]);

An object of arrays:

// Using object literal grammar
var obj = { "key": [value1, value2, value3], "key2": [value1, value2] } 

// Creating object properties using bracket or dot notation
var obj = {};
obj.key = [value1, value2, value3];
obj["key2"] = [value1, value2];