Advertisement
tonysamperi

009 - Array combinations recursively

Aug 14th, 2022 (edited)
872
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 0.41 KB | Source Code | 0 0
  1. function getCombos(arr) {
  2.   if (arr.length === 1) {
  3.     return [arr];
  4.   }
  5.   else {
  6.     const subarr = getCombos(arr.slice(1));
  7.     return [
  8.       ...[[arr[0]]],
  9.       ...subarr.map((e) => [arr[0], ...e]),
  10.       ...subarr,
  11.     ].sort((a, b) => a.length - b.length);
  12.   }
  13. }
  14.  
  15. console.info(JSON.stringify(getCombos(["a", "b", "c"])));
  16. // Output: [["a"],["b"],["c"],["a","b"],["a","c"],["b","c"],["a","b","c"]]
  17.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement