Skip to content

Instantly share code, notes, and snippets.

@vasanthv
Created May 7, 2018 07:40
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 vasanthv/08e8772d66dfd9e8c5d6df9901c30eb9 to your computer and use it in GitHub Desktop.
Save vasanthv/08e8772d66dfd9e8c5d6df9901c30eb9 to your computer and use it in GitHub Desktop.
Get combinations of all elements in an array with optional length filter.
//Based on https://stackoverflow.com/a/42531964
function combinations(array, length) {
const arr = new Array(1 << array.length).fill().map(
(e1, i) => array.filter((e2, j) => i & 1 << j));
return length ? arr.filter(a => a.length == length) : arr;
}
//console.log(combinations([1, 2, 3, 8, 10], 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment