vsync
vsync

Reputation: 130491

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); // [[],[],[]]

Upvotes: 20

Views: 23555

Answers (10)

Zum Dummi
Zum Dummi

Reputation: 233

best way to generate 2D array in js by ES6 by Array.from

function twodimension(input) {
  let index = 0,
    sqrt = Math.sqrt(input.length);

  return Array.from({
    length: sqrt
  }, (nothing, i) => Array.from({
    length: sqrt
  }, (nothingTwo, j) => input[index++]))
}

console.log(twodimension('abcdefghijklmnopqrstupwxy'))
console.log(twodimension([1,2,3,4,5,6,7,8,9]))

function input(length, fill) {
  let getNums = length * length;
  let fillNums = 1
  if (fill == 'minus') {
    return Array.from({
      length: length
    }, (nothing, i) => Array.from({
      length: length
    }, (nothingTwo, j) => getNums--))
  } else if (fill == 'plus') {
    return Array.from({
      length: length
    }, (nothing, i) => Array.from({
      length: length
    }, (nothingTwo, j) => fillNums++))
  }
  
  // you can dping snake ladders also with Array.from

  if (fill === 'snakes') {
    return Array.from({
        length: length
      }, (_, one) =>
      Array.from({
        length: length
      }, (_, two) => getNums--)
    ).map((el, i) =>
      i % 2 == 1 && length % 2 == 0 ? el.reverse() :
      i % 2 == 0 && length % 2 == 1 ? el.reverse() : el
    );
  }


}

console.log(input(8, 'minus'))
console.log(input(10, 'plus'))

console.log(input(5, 'snakes'))

you do anything with Array.from, it is easy to use and fast, this is the new method in ES6 syntax

Upvotes: 0

Allen
Allen

Reputation: 4789

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(() => [])

Upvotes: 8

Sergey Semushin
Sergey Semushin

Reputation: 124

var x = 3, y = 5, arr = Array(y).fill();
arr = arr.map(function(){return Array(x).fill(' ')});
console.log(arr);

Upvotes: 0

user1969453
user1969453

Reputation:

In ES6:

(m, n, initialElementValue) => Array(m).fill(Array(n).fill(initialElementValue))

Upvotes: 0

sugavaneshb
sugavaneshb

Reputation: 317

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

Upvotes: 3

user1542
user1542

Reputation: 49

for(var i=9,a=[];i>=0;i--){ a.push([]) }

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816860

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.

Upvotes: 25

Naftali
Naftali

Reputation: 146320

var a = [];
var max_length = 10;
for(var i = 0; i < max_length; ++i){ 
    a[i] = []; 
}

Upvotes: 0

malko
malko

Reputation: 2382

shorter way can be :

for(var i=9,a=[];i>=0;i--){ a.push([]) }

Upvotes: 0

Nathan Romano
Nathan Romano

Reputation: 7096

var a = []; for(var i=0;i<10;i++) { a[i] = []; }

Upvotes: 0

Related Questions