【问题标题】:Distribute, mix, merge... array with other ones分发,混合,合并...与其他数组
【发布时间】:2014-11-05 02:37:29
【问题描述】:

我的问题有点难以解释(因为我的英语说得不好)。 我正在用 Angular.js 开发一个应用程序,所以我们谈论 Javascript。

假设我们有 2 个这样的数组:

[
    [
      "Item 1",
      "Item 2"
    ],
    [
     "Item A",
     "Item B",
     "Item C"
    ]
]

我需要得到的是这样的:

[
  "Item 1 Item A",
  "Item 1 Item B",
  "Item 1 Item C",
  "Item 2 Item A",
  "Item 2 Item B",
  "Item 2 Item C"
]

但我认为真正的问题是我们可以有更多的数组(3、4、5...),并且每个数组中的项目数也在变化... 最后的想法是让每个项目只与其他项目连接一次。 有人有想法吗?

我尝试了 angular.forEach,for 循环...但我目前无法找到解决方案...

【问题讨论】:

  • 你想要的是 Cartesian Product
  • 是的,你是对的,我不记得它在数学中是怎么称呼的 :-)

标签: javascript arrays angularjs


【解决方案1】:

你想要的是这样的解决方案:

[
  ["Item 1", "Item 2"],
  ["Item A", "Item B", "Item C"]
].reduce(function(first, second) {
  var result = [];

  first.forEach(function(first) {
    var str = first + ' ';

    second.forEach(function(second) {
      result.push(str + second);
    });
  });

  return result;
});


结果:

[
  "Item 1 Item A", 
  "Item 1 Item B", 
  "Item 1 Item C", 
  "Item 2 Item A", 
  "Item 2 Item B", 
  "Item 2 Item C"
]


更新

有多个数组:

[
  ["Black", "White"],
  ["Apple", "Orange", "Pear"],
  ["Fast", "Slow",]
].reduce(function(firstArray, currentArray) {
  var result = [];

  firstArray.forEach(function(first) {
    var str = first + ' ';

    currentArray.forEach(function(second) {
      result.push(str + second);
    });
  });

  return result;
});


结果:

[
  // Black
  "Black Apple Fast",
  "Black Apple Slow",
  "Black Orange Fast",
  "Black Orange Slow",
  "Black Pear Fast",
  "Black Pear Slow",

  // White
  "White Apple Fast",
  "White Apple Slow",
  "White Orange Fast",
  "White Orange Slow",
  "White Pear Fast",
  "White Pear Slow"
]

【讨论】:

  • 如果有超过 2 个数组怎么办? OP 说:“真正的问题是我们可以有更多的数组 (3, 4, 5...)”
  • 用多个数组试试看输出。
  • 非常感谢您的帮助!我不知道reduce函数。这真的很有帮助!
猜你喜欢
  • 2011-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-05
相关资源
最近更新 更多