【问题标题】:create new array from combination of elements in array _ JavaScript从数组 _ JavaScript 中的元素组合创建新数组
【发布时间】:2020-06-01 14:37:03
【问题描述】:

假设我们有这个数组:

let a = ["a", "b", "c"]

我需要一些如下组合:

[["a"], ["b"], ["c"], ["a", "b"], ["a", "c"], ["b", "c"], ["b", "a"], ["c", "a"], ["c","b"], ["a", "b", "c"], ...]

const a = ["a", "b", "c"];

function perm(xs) {
  let ret = [];

  for (let i = 0; i < xs.length; i = i + 1) {
    let rest = perm(xs.slice(0, i).concat(xs.slice(i + 1)));

    if (!rest.length) {
      ret.push([xs[i]])
    } else {
      for (let j = 0; j < rest.length; j = j + 1) {
        ret.push([xs[i]].concat(rest[j]))
      }
    }
  }
  return ret;
}
console.log(perm(a));

随意编辑这个问题,如果这是一个类似的问题,请复制这个问题。strong text

【问题讨论】:

标签: javascript


【解决方案1】:

搜索了一会,发现有一个函数:

function combination(A, comb = [], result = [comb]) {
        for (var i = 0; i < A.length; i++)
            result = result.concat(combination(A.slice(0, i).concat(A.slice(i + 1)),            comb.concat(A[i])));
        return result;
    }
    
 console.log(combination(["q", "a", "w"]))

您可以使用 .slice(1, array.length)

删除第一个索引

【讨论】:

    猜你喜欢
    • 2017-01-30
    • 2023-03-12
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    相关资源
    最近更新 更多