Skip to content

Instantly share code, notes, and snippets.

@crutchcorn
Created March 30, 2020 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crutchcorn/1934c11d171284cc2292f488102920b9 to your computer and use it in GitHub Desktop.
Save crutchcorn/1934c11d171284cc2292f488102920b9 to your computer and use it in GitHub Desktop.
// Say you have an Iterable that you want to turn into an array
const map = new Map()
map.set('a', 1);
map.set('b', 2);
// Array.from has you covered!
const twoDArr = Array.from(map); // [['a', 1], ['b', 2]]
// Not only can Array.from handle Maps, it can create brand new arrays
const emptyArr = Array.from({length: 3}); // [blank, blank, blank];
// And as a second argument, it even accepts a map function
const toThreeArr = Array.from({length: 3}, (_, i) => i); // [0, 1, 2]
// You can easily make a "range" function from it!
const range = (from, to) => Array.from({length: (to - from) + 1}, (_, i) => i + from);
range(10, 15); // [10, 11, 12, 13, 14, 15]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment