11

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?

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
John Keats
  • 187
  • 2
  • 2
  • 9

1 Answers1

18

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];  
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 1
    okay, so using your "Creating object properties using bracket or dot notation" example i could get at a certain value in the following alert?: alert(obj["key2"][]) – John Keats May 09 '11 at 16:22
  • 1
    @William: yes, `alert(obj["key2"][0])` would alert the value of `value1`, `alert(obj["key2"][1])` would alert the value of `value2`. – Andy E May 09 '11 at 16:23