首页 > 解决方案 > 获取所有可能的数组组合

问题描述

我正在尝试创建一个输出数组,该数组由单个数组组成,这些数组包含使用递归的输入数组的每个组合。我在尝试弄清楚如何分离数组的元素时遇到问题。我想我需要以某种方式遍历数组并跟踪每个元素。

function getAllCombos(arr) {
  const output = [];

  function recursive(arr, combos = []) {
    if (arr.length === 0) return output.push(combos);
    combos.push(arr);
    recursive(arr.slice(1), [...combos])
  }
  recursive(arr);
  return output
}

// To check if you've completed the challenge, uncomment this code!
console.log(getAllCombos(['a', 'b'])); // -> [['a','b'], ['a'], ['b'], []]

标签: javascriptarraysrecursion

解决方案


推荐阅读