Last active
April 12, 2018 18:49
-
-
Save edumelzer/7011cdbfad7987a63887024842f0bda4 to your computer and use it in GitHub Desktop.
Get all combinations in array with a given size
This file contains hidden or 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
const getArrCombos = (arr, comboSize) => { | |
let combos = arr.reduce( (acc, v, i) => { | |
if (comboSize === 1) { | |
return acc.concat([[v]]) | |
} else { | |
arrCombo = getArrCombos(arr.slice(i+1), comboSize - 1); | |
return acc.concat(arrCombo.map( w => [v].concat(w))); | |
} | |
}, []); | |
//Combos for $arr, with size of $comboSize | |
return combos | |
} | |
console.log(getArrCombos([1,2,3,4], 2)) | |
// expected output: [ [1,2], [1,3], [1,4], [2,3], [2,4], [3,4] ] | |
console.log(getArrCombos(['Rice', 'Beef', 'Fries', 'Coke'], 3)) | |
/** | |
* expected output: | |
* [ | |
* ["Rice", "Beef", "Fries"], | |
* ["Rice", "Beef", "Coke"], | |
* ["Rice", "Fries","Coke"], | |
* ["Beef", "Fries","Coke"] | |
* ] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment