Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to generate empty 2D array

is there a shorter, better way to generate 'n' length 2D array?

var a = (function(){ var i=9, arr=[]; while(i--) arr.push([]); return arr })();

a // [ [],[],[],[],[],[],[],[],[] ]

** old-school short-way**:

var a = (function(a){ while(a.push([]) < 9); return a})([]);

UPDATE - Using ES2015

Array(5).fill().map(a=>[]); // will create 5 Arrays in an Array
// or
Array.from({length:5}, a=>[])

Emptying 2D array (saves memory rather)

function make2dArray(len){
    var a = [];
    while(a.push([]) < len); 
    return a;
}

function empty2dArray(arr){
    for( var i = arr.length; i--; )
      arr[i].length = 0;
}

// lets make a 2D array of 3 items
var a = make2dArray(3);

// lets populate it a bit
a[2].push('demo');
console.log(a); // [[],[],["demo"]]

// clear the array
empty2dArray(a);
console.log(a); // [[],[],[]]
like image 733
vsync Avatar asked Jun 27 '11 15:06

vsync


People also ask

How do you create an empty 2D array in Java?

To create an empty array, you can use an array initializer. The length of the array is equal to the number of items enclosed within the braces of the array initializer. Java allows an empty array initializer, in which case the array is said to be empty.

How do you initialize a 2D array?

To declare a 2D array, specify the type of elements that will be stored in the array, then ( [][] ) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference.

Can we initialize 2D array without size?

You can create a two-dimensional array without specifying both dimensions like int[4][] is a valid array declaration. It also allows you to create a multi-dimensional array whose rows can vary in length, as we have seen in our second example.


3 Answers

Another way:

for(var a = [];a.length < 10; a.push([])); // semicolon is mandatory here

Yet another way:

var a = []; while(a.push([]) < 10);

This works because .push() [docs] (specification) returns the new length of the array.


That said, this is the wrong way of "reducing code". Create a dedicated function with a meaningful name and use this one. Your code will be much more understandable:

function get2DArray(size) {
    size = size > 0 ? size : 0;
    var arr = [];

    while(size--) {
        arr.push([]);
    }

    return arr;
}

var a = get2DArray(9);

Code is read much more often than written.

like image 143
Felix Kling Avatar answered Sep 29 '22 00:09

Felix Kling


Just discovered another ES6 way with one line expression:

Array.from({length: N}, () => [])

Array.from(arrayLike[, mapFn[, thisArg]])

More detail about its implementation/polyfill ⇢ MDN Array.from()

Yet another neat solution with help of array spread syntax:

[...Array(N)].map(() => [])
like image 37
lxyyz Avatar answered Sep 29 '22 01:09

lxyyz


Array(cardinality).fill(0).map(function(item) {return [];});

where cardinality is the number of items you are looking at. In this case it would be 9. This was suggested by one of my colleagues actually. This is neat, I think :) This is valid from ECMA V6. Documentation: Array::fill

like image 27
sugavaneshb Avatar answered Sep 29 '22 01:09

sugavaneshb