I have been reading online and some places say it isn\'t possible, some say it is and then give an example and others refute the example, etc.
How do I dec
Array.from(Array(2), () => new Array(4))
2 and 4 being first and second dimensions respectively.
We are making use of Array.from, which can take an array-like param and an optional mapping for each of the elements.
Array.from(arrayLike[, mapFn[, thisArg]])
var arr = Array.from(Array(2), () => new Array(4));
arr[0][0] = 'foo';
console.info(arr);
The same trick can be used to Create a JavaScript array containing 1...N
n = 10,000)Array(2).fill(null).map(() => Array(4))
The performance decrease comes with the fact that we have to have the first dimension values initialized to run .map. Remember that Array will not allocate the positions until you order it to through .fill or direct value assignment.
var arr = Array(2).fill(null).map(() => Array(4));
arr[0][0] = 'foo';
console.info(arr);
Here's a method that appears correct, but has issues.
Array(2).fill(Array(4)); // BAD! Rows are copied by reference
While it does return the apparently desired two dimensional array ([ [ <4 empty items> ], [ <4 empty items> ] ]), there a catch: first dimension arrays have been copied by reference. That means a arr[0][0] = 'foo' would actually change two rows instead of one.
var arr = Array(2).fill(Array(4));
arr[0][0] = 'foo';
console.info(arr);
console.info(arr[0][0], arr[1][0]);
I found below is the simplest way:
var array1 = [[]];
array1[0][100] = 5;
alert(array1[0][100]);
alert(array1.length);
alert(array1[0].length);
The easiest way:
var myArray = [[]];
This is what i achieved :
var appVar = [[]];
appVar[0][4] = "bineesh";
appVar[0][5] = "kumar";
console.log(appVar[0][4] + appVar[0][5]);
console.log(appVar);
This spelled me bineeshkumar
var playList = [
['I Did It My Way', 'Frank Sinatra'],
['Respect', 'Aretha Franklin'],
['Imagine', 'John Lennon'],
['Born to Run', 'Bruce Springsteen'],
['Louie Louie', 'The Kingsmen'],
['Maybellene', 'Chuck Berry']
];
function print(message) {
document.write(message);
}
function printSongs( songs ) {
var listHTML;
listHTML = '<ol>';
for ( var i = 0; i < songs.length; i += 1) {
listHTML += '<li>' + songs[i][0] + ' by ' + songs[i][1] + '</li>';
}
listHTML += '</ol>';
print(listHTML);
}
printSongs(playList);
Few people show the use of push:
To bring something new, I will show you how to initialize the matrix with some value, example: 0 or an empty string "".
Reminding that if you have a 10 elements array, in javascript the last index will be 9!
function matrix( rows, cols, defaultValue){
var arr = [];
// Creates all lines:
for(var i=0; i < rows; i++){
// Creates an empty line
arr.push([]);
// Adds cols to the empty line:
arr[i].push( new Array(cols));
for(var j=0; j < cols; j++){
// Initializes:
arr[i][j] = defaultValue;
}
}
return arr;
}
usage examples:
x = matrix( 2 , 3,''); // 2 lines, 3 cols filled with empty string
y = matrix( 10, 5, 0);// 10 lines, 5 cols filled with 0