Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of arrays in Javascript

I'm trying to make a list of arrays in JAVASCRIPT but my program doesn't do what I expect.

I want to make a list of arrays like this:

var myListofArrays;

var firstArray = [1,2,3,4,5,6];
var secondArray = [6,5,4,3,2,1];
var thirdArray = [1,1,1];

I want to add those arrays in myListArray to finally get something like that:

myListofArrays[0] = [1,2,3,4,5,6];
myListofArrays[1] = [6,5,4,3,2,1];
myListofArrays[2] = [1,1,1];

Anyone knows how to do it?

Thank you very much!

like image 636
carles.sole.grau Avatar asked Dec 03 '22 14:12

carles.sole.grau


2 Answers

Starting from:

var firstArray = [1,2,3,4,5,6];
var secondArray = [6,5,4,3,2,1];
var thirdArray = [1,1,1];

You only need create a new array object:

var myListOfArrays = [];

and then, insert all arrays that you want into the new array:

mylistOfArrays.push(firstArray);
mylistOfArrays.push(secondArray);
mylistOfArrays.push(thirdArray);

With push() method the array object is added at end of the new array. This method also returns the new length.

You can visit this reference to get a detailed list of array methods: Array Methods

like image 77
ivanfr90 Avatar answered Dec 05 '22 03:12

ivanfr90


There are many ways to do this. Try:

var myListofArrays = [];

var firstArray = [1,2,3,4,5,6];
var secondArray = [6,5,4,3,2,1];
var thirdArray = [1,1,1];

myListofArrays.push(firstArray);
myListofArrays.push(secondArray);
myListofArrays.push(thirdArray);

Or a little fancier:

myListofArrays.push(firstArray, secondArray, thirdArray);

Or:

var firstArray = [1,2,3,4,5,6],
    secondArray = [6,5,4,3,2,1],
    thirdArray = [1,1,1],
    myListOfArrays = [firstArray, secondArray, thirdArray];

And there are still probably plenty other valid ways to do this.

like image 22
Andrew Clavin Avatar answered Dec 05 '22 03:12

Andrew Clavin