Skip to content

Instantly share code, notes, and snippets.

@edumelzer
Last active April 12, 2018 18:49
Show Gist options
  • Save edumelzer/7011cdbfad7987a63887024842f0bda4 to your computer and use it in GitHub Desktop.
Save edumelzer/7011cdbfad7987a63887024842f0bda4 to your computer and use it in GitHub Desktop.
Get all combinations in array with a given size
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