Created
May 7, 2018 07:40
-
-
Save vasanthv/08e8772d66dfd9e8c5d6df9901c30eb9 to your computer and use it in GitHub Desktop.
Get combinations of all elements in an array with optional length filter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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