JavaScript 中的所有数组组合 [英] All Array Combination in JavaScript

查看:21
本文介绍了JavaScript 中的所有数组组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要数组的所有可能组合,包括组合的反向组合.

Need all possible combinations of an array including the reverse of a combination too.

例如:

var b = ['a1','b1','a','b'];

需要组合为:

a1,b1,a,b
a1b1,a1a,a1b, b1a1,b1a,b1b, ......,
a1b1a,a1b1b,a1ab1,a1bb1,........,
a1b1ab,a1b1ba.....bab1a1

所有 64 种组合(如果数组有 4 个元素).我使用 ArrayList 和 Collection API 在 java 中找到了解决方案,但现在我需要一个纯 JavaScript ES5 解决方案.

All 64 combinations (if array has 4 elements). I found solution in java using ArrayList and Collection API, but right now I need a pure JavaScript ES5 solution.

我尝试了以下方法,但只能提供较少的组合.

I tried the following, but it only provides lesser combinations.

function getCombinations(chars) {
    var result = [];
    var f = function (prefix, chars) {
        for (var i = 0; i < chars.length; i++) {
            result.push(prefix + chars[i]);
            f(prefix + chars[i], chars.slice(i + 1));
        }
    }
    f('', chars);
    return result;
}

推荐答案

让我们用文字表达您的要求:对于每个起始元素,附加其余元素的所有组合的所有排列.

Let's put your request into words: for each starting element, append all permutations of all combinations of the rest of the elements.

function f(A, comb=[], result=[comb]){
  return A.reduce((acc, a, i) => acc.concat(f(A.slice(0,i).concat(A.slice(i+1)), comb.concat(a))), result);
}

console.log(JSON.stringify(f(['a', 'b', 'c', 'd'])));

这篇关于JavaScript 中的所有数组组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆