从javascript中的多维数组中获取所有变体 [英] Get all variants from a multidimensional array in javascript

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

问题描述

我在js中有以下数组:

I have the following array in js:

var list = [
  ['nice', 'delicious', 'red'],
  ['big', 'tiny'],
  ['apple']
];

我想获得所有可能的变化,例如:

I'd like to get all the possible variations, like:

['nice', 'big', 'apple']
['delicious', 'big', 'apple']
['red', 'big', 'apple']
['nice', 'tiny', 'apple']
...

实现这一目标的最佳/最有说服力的方法是什么?

What is the best / most eloquent way to achieve this?

推荐答案

我试图提出一些非常喜欢递归或叠加地图的东西并减少,但这个问题似乎不够复杂,足以证明不同的东西:

I was trying to come up with something really fancy like recursion or stacks of maps and reduces, but this questions seems not as complicated enough to justify something different than:

var result = list[0].map(function(item) { return [item]; });

for (var k = 1; k < list.length; k++) {
    var next = [];
    result.forEach(function(item) {
        list[k].forEach(function(word) {
            var line = item.slice(0);
            line.push(word);
            next.push(line);
        })
    });
    result = next;
}

console.log(result);

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

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