【问题标题】:Javascript: all arrangements of n arrays with n values [duplicate]Javascript:具有n个值的n个数组的所有排列[重复]
【发布时间】:2018-11-06 20:34:21
【问题描述】:

如果我有这样的收藏:

var array = {
    "fruit": ["apple","banana"],
    "amount": ["1", "2", "3"],
    "orign": ["africa", "asia", "europe"],
    ...
    "n": ["0", "...", "n"]
}

我怎样才能得到这样的 JSON 格式的所有组合:

[
 {
   "fruit": "apple",
   "amount": "1",
   "orign": "africa"
 }
 {
   "fruit": "apple",
   "amount": "1",
   "orign": "asia"
 }
 ...
]

是否可以以迭代方式遍历所有元素?还是我最终会写 n 个循环?

【问题讨论】:

  • 你可以这样做:const arrays = Object.values({ "fruit": ["apple","banana"], "amount": ["1", "2", "3"], "orign": ["africa", "asia", "europe"] }); const f = (a, b) => [].concat(...a.map(d => b.map(e => [].concat(d, e)))); const cartesian = (a, b, ...c) => (b ? cartesian(f(a, b), ...c) : a); console.log(cartesian(...arrays));

标签: javascript arrays json loops


【解决方案1】:

我相信您正在寻找“笛卡尔积”(假设数组是集合)。您的问题(以略微不同的方式)之前已在 here 中讨论过。您可以在其中看到不同的解决方案,包括递归解决方案和许多类似的函数式编程。

希望对你有帮助

干杯!

【讨论】:

  • 感谢您的快速响应!笛卡尔积似乎是正确的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-24
  • 2018-03-11
  • 2011-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多