组合两个数组中的元素的逻辑(Javascrip / Typescript)

时间:2018-09-27 06:51:55

标签: javascript typescript

此处提到的两种数组格式

const arr1 = [
  {
    "elementName": "one"
  },
  {
    "elementName": "two"
  }
]

const arr2 = [
  {
    "type": "RPT_PROPERTY_DEMOGRP",
    "values": [
      {
        "label": "HH"
      },
      {
        "label": "HH1"
      }
    ]
  },
  {
    "type": "RPT_PROPERTY_PLAYBACK_TYPE",
    "values": [
      {
        "label": "WW"
      },
      {
        "label": "WW1"
      }
    ]
  }
]

这两个我需要组合

  1. “一个HH WW”

    “一个HH WW1”

    “一个HH1 WW”

    “一个HH1 WW1”

    “两个HH WW”

    “两个HH WW1”

    “两个HH1 WW”

    “两个HH1 WW1”

如何在js或ts中为此编写逻辑

2 个答案:

答案 0 :(得分:2)

您可以使用迭代和递归的方法。

const
    cartesian = (a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []),
    arr1 = [{ elementName: "one" }, { elementName: "two" }]
    arr2 = [{ type: "RPT_PROPERTY_DEMOGRP", values: [{ label: "HH" }, { label: "HH1" }] }, { type: "RPT_PROPERTY_PLAYBACK_TYPE", values: [{ label: "WW" }, { label: "WW1" }] }],
    result = [
            arr1.map(({ elementName }) => elementName),
            ...arr2.map(({ values }) => values.map(({ label }) => label))
        ].reduce(cartesian);

console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

您要寻找笛卡尔积:https://eddmann.com/posts/cartesian-product-in-javascript/

const set1 = arr1.map(elt => elt.elementName);
const set2 = arr2.map(elt => elt.values.map(val => val.label));
const dataSet = [set1, ...set2];
dataSet.reduce((acc, set) => acc.map(x => set.map(y => [x, y].flatten())).flatten())