John Keats John Keats - 3 months ago 39x
Javascript Question

How to initialize a jagged array in JavaScript?

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?


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];