我在Javascript中有一个String类型的数组。 例如:[" ab"," cd"," ef"," gh"] 这个阵列不是固定的。按字母顺序排列。
我想要这样的输出:
ab
abcd
abef
abgh
abcdef
abcdgh
abefgh
abcdefgh
cd
cdef
cdgh
cdefgh
ef
efgh
答案 0 :(得分:2)
使用此功能创建x
的{{3}}:
function power(x) {
var r = [""], // start with empty set/string
l = 1;
for (var i=0; i<x.length; l=1<<++i) // OK, l is just r[i].length, but this looks nicer :)
for (var j=0; j<l; j++) {
r.push(r[j].slice(0)); // copy
r[j] += x[i];
}
return r;
}
用法:
> power(["ab", "cd", "ef", "gh"])
["abcdefgh", "cdefgh", "abefgh", "efgh", "abcdgh", "cdgh", "abgh", "gh", "abcdef", "cdef", "abef", "ef", "abcd", "cd", "ab", ""]
答案 1 :(得分:0)
我同意罗宾的说法,你应该先尝试自己,但这里是(在lodash图书馆的帮助下):
function combos(arr) {
if(arr.length <= 1) return arr
return _.flatten(arr.map(function(key, index) {
return [[key]].concat(
combos(arr.slice(index+1))
.map(function(combo) { return [key].concat(combo) })
)
}))
}
console.log(
combos(["a", "b", "c", "d"])
.map(function(arr) { return arr.join("")})
)