DEV Community

Cover image for Few neat JS snippets
Som Shekhar Mukherjee
Som Shekhar Mukherjee

Posted on

Few neat JS snippets

Creating a 2D Array initialized with zeroes

const nrows = 5;
const ncols = 5;
const arr = Array.from({ length: nrows }, () =>
  Array.from({ length: ncols }, () => 0)
);
Enter fullscreen mode Exit fullscreen mode

Flattening a 2D array into a 1D array

const oneD = [].concat(...twoDArr);
Enter fullscreen mode Exit fullscreen mode

Array.from() can be really handy at times

const primes = [2, 3, 5, 7, 11];
const sqPrimes = Array.from(primes, (x) => x * x);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)