最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - 2-dimensional arrays in ES6 - Stack Overflow

programmeradmin4浏览0评论

Long story short, i'm looking for a way to create and fill 2D arrays using ES6, in an effort to avoid for loops. The created array should contain all 0s. I've tried many different approaches so i cant post all of them.

var [r, c] = [5, 5]; 
var m = Array(r).fill(Array(c).fill(0));

This works but it creates a bunch of instances of the same array, and adding slice Array(r).fill(Array(c).fill(0).slice()); doesn't help either.

I also tried creating the empty arrays and then looping trough them but that's a whole different problem, you apparently can't forEach() or map() an empty array, and i couldn't even loop through a filled one efficiently.

Am i missing something here? Are a whole lot of for loops the best way to approach this? It looks really messy and overly long. Any help appreciated.

Long story short, i'm looking for a way to create and fill 2D arrays using ES6, in an effort to avoid for loops. The created array should contain all 0s. I've tried many different approaches so i cant post all of them.

var [r, c] = [5, 5]; 
var m = Array(r).fill(Array(c).fill(0));

This works but it creates a bunch of instances of the same array, and adding slice Array(r).fill(Array(c).fill(0).slice()); doesn't help either.

I also tried creating the empty arrays and then looping trough them but that's a whole different problem, you apparently can't forEach() or map() an empty array, and i couldn't even loop through a filled one efficiently.

Am i missing something here? Are a whole lot of for loops the best way to approach this? It looks really messy and overly long. Any help appreciated.

Share Improve this question asked Mar 4, 2018 at 0:43 Mare_413Mare_413 4175 silver badges13 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 10

Doing this worked for me:

var [r, c] = [5, 5]; 
var m = Array(r).fill().map(()=>Array(c).fill(0));

Basically just filling it with a dummy value so you can map over it

You could use Array.from that takes a callback function and inside return arrays with 0's using fill method.

const arr = Array.from(Array(2), () => Array(5).fill(0))
console.log(arr)

Or you could just create array where each element is number of elements in sub-array and then use map and fill methods.

const arr = [5, 5].map(e => Array(e).fill(0))
console.log(arr)

For those needing the same thing but with undefined as each value this also works.

const x = 100;
const y = 100;
const grid = [...new Array(x)].map(() => [...new Array(y)]);

To fill the array simply map the inner value. This will make an array filled with 0 for each value.

const x = 100;
const y = 100;
const grid = [...new Array(10)].map(() => [...new Array(10)].map(() => 0));

const nthArray = (n) => Array.from(Array(n), () => Array(5).fill(0))

const arr = nthArray(3);

console.log(arr);

发布评论

评论列表(0)

  1. 暂无评论