Few neat JS snippets

somshekhar

Som Shekhar Mukherjee

Posted on November 9, 2020

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
💖 💪 🙅 🚩
somshekhar
Som Shekhar Mukherjee

Posted on November 9, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related