Javascript array with index in declaration - javascript

I'm running a js code and in some part of it there is a definition of an array which I don't get what it means , it looks like this :
var myArray = new Array();
myArray[myNum] = new Array();
myArray[myNum].push(value1);
I don't get why there is an index of the array at the second line , is it a two dimensional array ? I'll appreciate if you can help me with this. thanks

var myArray = new Array();
Creates an array.
myArray[myNum] = new Array();
Creates an array in myArray's myNum index.
myArray[myNum].push(value1);
Stores valuea1 into the array (adds the element at the last, in this case at 0-th index) stored in myArray[myNum].
Yes, your assumption is right - after the execution of the three statements a two dimensional array is created, which looks something like this -
[....., [value1], ......] // the inner array is stored at "myNum" index
To access value1, you can now do -
myArray[myNum][0];
See the doc for push.

This code just creates an array with an array at index myNum. Lets break the code down.
var myArray = new Array();
//Create a new array
myArray[myNum] = new Array();
//At index 'myNum' which is a variable presumably holding an index - create a new array
myArray[myNum].push(value1);
//push variable `value1` to the new array at index myNum of myArray.

Let me try to explain your code....
Explanation:
var myArray = new Array(); // (1)
myArray[myNum] = new Array(); // (2)
myArray[myNum].push(value1); // (3)
(1) This creates a new empty array . It could be 1D, 2D, 3D. Currently it has nothing. At this point you array should look like this..
myArray= [];
(2) This creates another empty Array in "myArray" at index "myNum". Let us assume myNum=5;
So
myArray[5] = new Array();
Will give
myArray =[[]];
(3) This will push value1 into myArray at index "myNum". Let us again assume myNum=5 and value1 = 1,2,3;
So
myArray[5].push(1,2,3);
Will give
myArray=[[1,2,3]]
DEMO IN A FIDDLE

Related

variable values to store a array

how can I variable values to store a array?
Look my code:
var collection =normal,user,student ;
var array = [collection];
alert(array[0]);
In this case, alert would popup a normal,user,student. but i need an array such as array[0] get normal,array[1] get user,array[2] get student like that
how it is possible
Is there any chance to convert such variable into a JS array?
As normal,user,student are values. You can use split() to split the string using , as deliminator then indexes can be used to access elements.
var collection = "normal,user,student";
var array = collection.split(',');
console.log(array[0]);
There are many, many ways to create arrays ... some examples:
// just declare an array directly
var array1 = ["normal", "user", "student"];
console.log(array1[0]);
// use split to create an array out of a string
var collection = "normal,user,student";
var array2 = collection.split(",");
console.log(array2[1]);
// use split and map to create an array by your needs
var collection = " normal, user , student ";
var array3 = collection.split(",").map(function(value) {
return value.trim();
});
console.log(array3[2]);
// push each value to the array
var array4 = [];
array4.push("normal");
array4.push("user");
array4.push("student");
console.log(array4[0]);
// ...
var collection = "normal,user,student";
var jsarray = collection.split(",");
alert(jsarray[0]);
alert(jsarray[1]);
alert(jsarray[2]);
Are you trying to add the existing variables to the array? If so you are just missing your square brackets:
var collection = [normal, user, student];
If you would like the elements to contain the string values, you would do it like this:
var collection = ["normal", "user", "student"];

Why pushing array into another array merges the elements instead of putting them in separate array

I have a array into which I push new values iteratively, at the end of each iteration I want the array formed to be inserted into new array.
Ex: if at the end of first iteration array=[1,2,3,4], then bigarray=[[1,2,3,4]].
After 2nd iteration, if array=[5,6,7,8], then bigarray=[[1,2,3,4],[5,6,7,8]] and so on.
So basically bigarray is to contain a list of arrays out of which I can obtain arrays.
ex: bigarray[0] should give me a array [1,2,3,4]
What I am doing now is array.push(some values) and at the end bigarray.push(array). Doing this merges all the values into a single array like this
bigarray=[1,2,3,4,5,6,7,8] out of which I can separate first array and second array.
piece of code:
var array=[];
for(var i=0; i<range;i++){
var arraychart=[];
var jan= resp.ChartDataList[i].jan;
arraychart.push(jan);
var feb= resp.ChartDataList[i].feb;
arraychart.push(feb);
var mar= resp.ChartDataList[i].mar;
arraychart.push(mar);
var apr= resp.ChartDataList[i].apr;
arraychart.push(apr);
var may= resp.ChartDataList[i].may;
arraychart.push(may);
var jun= resp.ChartDataList[i].jun;
arraychart.push(jun);
//var jan= resp.ChartDataList[i].jan;
array.push(arraychart);
alert (arraychart);
}
alert(array);
How do I achieve the above desired result??
You should call array.push in this way (array.push([1,2,3])) instead of (array.push(1,2,3))
var bigarray = [];
bigarray.push( [1,2,3,4] );
bigarray.push( [5,6,7,8] );
console.log(bigarray); // prints [[1,2,3,4],[5,6,7,8]]
EDIT
After seeing your code, you don't have problems in your code, just print the array using console.log instead of alert, because alert will call .toString() of the big array, and flatten it
U can try something like this
bigArrray[bigArray.length] = subArray
But...
bigArrray.push([1,2,3])
...works as well for me

javascript re-populate an array

I am using:
var myArry = [];
as a global variable. I then populate the array with some data from the database.
If I then want to replace the array data with new data do I have to empty / reset the original array.
Or what is the correct method?
Here are some ways to empty an array:
myArray = [];
myArray = new Array();
myArray.length = 0;
myArray.splice(0, myArray.length);
These will all work.
myArray.length = 0; will empty the array. You can then repopulate it as needed.
If it comes from the database, it would be better to clear your array since some data may be deleted.
To do so, you can write myArray = [];

How to create empty 2d array in javascript?

How do I create an empty 2D array in Javascript (without knowing how many rows or columns there will be in the new array)?
If it's a simple array var newArray = new Array(); I can assign as many elements as I want. But what about a 2D array? Can I create one without specifying the numbers of rows and columns? and how do I access the elements afterwards (myArray[0][1] or myArray[0,1])?
You can create a 6 x 6 empty array like this:
var myGrid = [...Array(6)].map(e => Array(6));
Array(6) generates an array with length = 6 and full of undefined values.
We map that array to another array full of undefined values.
In the end, we get a 6x6 grid full of undefined positions.
If you need to initialize the grid with a default value:
var value = 'foo'; // by default
var myGrid = [...Array(6)].map(e => Array(6).fill(value));
Now you have a 6 x 6 grid full of 'foo'.
Yes you can create an empty array and then push data into it. There is no need to define the length first in JavaScript. Check out jsFiddle Live Demo
Define:
const arr = [[],[]];
Push data:
arr[0][2] = 'Hi Mr.A';
arr[1][3] = 'Hi Mr.B';
Read data:
alert(arr[0][2]);
alert(arr[1][3]);
Update:
Here is also a video recommended by Brady Dowling:
Create a 2D array: ([https://www.youtube.com/watch?v=tMeDkp1J2OM][2])
There are no two dimensional arrays in Javascript.
To accomplish the effect of a two dimensional array, you use an array of arrays, also known as a jagged array (because the inner arrays can have different length).
An empty jagged array is created just like any other empty array:
var myArray = new Array();
You can also use an empty array literal:
var myArray = [];
To put any items in the jagged array, you first have to put inner arrays in it, for example like this:
myArray.push([]);
myArray[0][0] = 'hello';
You can also create an array that contains a number of empty arrays from start:
var myArray = [[],[],[]];
That gives you a jagged array without any items, but which is prepared with three inner arrays.
As it's an array of arrays, you access the items using myArray[0][1].
Say you wanted to make a 2d array (i.e. matrix) that's 100x100, you can do it in one line, like this:
var 2darray = new Array(100).fill(null).map(()=>new Array(100).fill(null));
This will create a 100x100 matrix of NULL's.
Replace the 100x100 with whatever dimensions you want, and the null's with whatever is your prefered default value, or blank for undefined.
You can use a simple for loop to create an array of the approximate size and then push more rows if need be.
const arr = [];
const n = 7;
const m = 5;
for (let i = 0; i < n; i++) {
arr.push(new Array(m).fill(0));
}
const arr = [];
const n = 7;
const m = 5;
for (let i = 0; i < n; i++) {
arr.push(new Array(m).fill(0));
}
console.log(arr);
var myArray = [
["cats","dogs","monkeys","horses"],
["apples","oranges","pears","bananas"]
];
document.write(myArray[0][2]) //returns "monkeys"
Two things:
1) The array length property improperly reports the array length if called after the var myArray = [[],[]]; statement. Technically, since the empty arrays are defined, they are getting counted by the length property, but in the spirit of the length property it really should return 0, because no non-empty elements have been added to any of the arrays.
A minimum work around is to use two nested for( in ) loops, one for the 1st array and one for the 2nd array, and to count the non-undefined elements.
2) Extending Siamak A.Motlagh example and adding a arr([2][4]) = 'Hi Mr.C'; assignment fails with an "Uncaught TypeError: Cannot set property '4' of undefined" error.
See the jsFiddle: http://jsfiddle.net/howardb1/zq8oL2ds/
Here is a copy of that code:
var arr = [[],[]];
alert( arr.length ); // wrong!
var c = 0;
for( var i in arr )
for( var j in arr[ i ] )
if( arr[ i ][ j ] != undefined )
++c;
alert( c ); // correct
arr[0][2] = 'Hi Mr.A';
alert(arr[0][2]);
arr[1][3] = 'Hi Mr.B';
alert(arr[1][3]);
arr[2][4] = 'Hi Mr.C'; // At this point I'm getting VM558:62 Uncaught TypeError: Cannot set property '4' of undefined
alert(arr[2][4]);
var c = 0;
for( var i in arr )
for( var j in arr[ i ] )
if( arr[ i ][ j ] != undefined )
++c;
alert( c );
Why does the third assignment fail? What about the [[],[]] creation statement told it that the first array was valid for 0 and 1, but not 2 or that 2 and 3 were ok for the second array, but not 4?
Most importantly, how would I define an Array in an Array that could hold date objects in the first and second arrays. I'm using the jQuery-UI DatePicker, which expects an array of dates, as in date objects, which I've extended to use a second date array to contain date objects that contain times so I can keep track of multiple dates, and multiple times per day.
Thanks.
The functions I use
function get_empty_2d_array(numRows, numColumnns) {
return [...Array(numRows)].map(e => Array(numColumnns));
}
function get_2d_array_filled(numRows, numColumnns, fillValue) {
return [...Array(numRows)].map(e => Array(numColumnns).fill(fillValue));
}
This also works as an expression:
var twoDarr= new Array(desiredLength);
for (i=0;i<twoDarr.length;i++) {twoDarr[i]=[];}
I don't know how it pars in terms of performance with the rest of the answers here, if you have a clue let me know in the comments.
If you don't know the length of the array beforehand pls have in mind that you can use either push([]), or splice() if you want to push/remove/replace a new element in place of an existing one.
const grid = new Array(n).fill(new Array(n))

Javascript multidimentional array undefined object error

I am trying to make a two dimensional array out of two one dimentional arrays with this code:
var PassAssoArr = new Array();
for(k in PassPourcentNames) {
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
However, I get the error message: " 'undefined' is null or not an object " and it points to the first line after the for statement.
PassPourcentNames and PassPourcentValue have the same number of elements and none of the values are null. The first one contain strings and the second one integers.
Any help is greatly apreciated.
var PassAssoArr = new Array();
for(k in PassPourcentNames) {
PassAssoArr[k] = new Array();
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
Also instead of new Array() you can use []
var PassAssoArr = [];
for(k in PassPourcentNames) {
PassAssoArr[k] = [];
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
I believe this is actually faster in most JS engines.
First define PassAssoArr[k] = []; before assigning to [0] and [1].
Javascript does not support true multi-dimensional arrays.
You're trying to use nested arrays without creating the inner arrays.
You need to put an array into each element of the outer PassAssoArr:
PassAssoArr[index] = []; //Empty array literal
You're only defining one dimension of PassAssoArr - you need to set PassAssoArr[k] = new Array();
Try just doing:
PassAssoArr[k] = new Array(PassPourcentNames[k], PassPourcentValue[k]);

Categories