Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 462
John Keats Avatar asked May 09 '11 16:05

John Keats


People also ask

How do you declare a jagged array?

A jagged array is an array whose elements are arrays, possibly of different sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays. jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[2];

How do you initialize an array in JavaScript?

You can initialize an array with Array constructor syntax using new keyword. The Array constructor has following three forms. Syntax: var arrayName = new Array(); var arrayName = new Array(Number length); var arrayName = new Array(element1, element2, element3,...

What is jagged array in JS?

A jagged array is an array that contains a combination of numbers and other arrays. The arrays can be multiple levels deep. The goal of the function is to find the sum of all the numbers inside the jagged array.

Does JavaScript support 2D arrays?

JavaScript supports 2D arrays through jagged arrays – an array of arrays.


1 Answers

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];  
like image 165
Andy E Avatar answered Oct 12 '22 23:10

Andy E