CodingTrain / Suggestion-Box

A repo to track ideas for topics
572 stars 86 forks source link

More on arrays in JS #100

Open shiffman opened 8 years ago

shiffman commented 8 years ago

Following up from 2D array video #46, this interesting solution was pointed out to me in the YouTube comments:

make2Darr = function(r, c) { 
  return new Array(c).fill([]).map(e => new Array(r)); 
}

Would love to investigate fill() and map() in a future video. What else? There is also #89 which relates to this topic.

XavilPergis commented 8 years ago

I also came up with a way to make a "square" n-dimensional array.

// n: number of dimensions
// r: size of each dimension
// f: what to fill the array with. If left blank, it will be filled with undefined.
let ndarr = function(n, r, f) {
    if(n == 1) return new Array(r).fill(f);
    else return new Array(r).fill(ndarr(n - 1, r));
};

Basically, it makes an array, fills it with empty arrays, fills all those with empty arrays, etc. until the correct number of dimensions is reached.

Don't really know why this would be useful, but it does demonstrate recursion pretty well. :D

MAKIO135 commented 8 years ago

Array.fill / Array.map / Array.forEach / Array.reduce / Array.some / Array.every And a word on functionnal programming paradigm :)

GreyWizard1955 commented 7 years ago

I -=LOVE=- XavilPergis ideas!!! In the live stream, when Daniel was doing the n-dimensional array, he did a really good job; but knowing how hot it was that day, he lost a lot of his "steam"... In the cool of the winter, he should readdress the issue, and put in some of MAKIO135 ideas...

(I -=LOVE=- arrays!!!)

meiamsome commented 7 years ago

Why not:

ndarr = function(){return new Array(arguments[0]||0).fill(0).map(ndarr.bind.apply(ndarr, arguments));}

This clearly legible code lets you generate any n-dimensional array:

ndarr(1, 2);
// [ [ [], [] ] ]
ndarr(3, 4, 2);
// [ [ [ [], [] ], [ [], [] ], [ [], [] ], [ [], [] ] ], [ [ [], [] ], [ [], [] ], [ [], [] ], [ [], [] ] ], [ [ [], [] ], [ [], [] ], [ [], [] ], [ [], [] ] ] ]