如何生成笛卡尔积?

作者站长头像
站长
· 阅读数 5

现在有这几个数据

let names = ["iPhone X", "iPhone XS"]

let colors = ["黑色", "白色"]

let storages = ["64g", "256g"]

要转换成

[
    {
        "spec": [
            {
                "name": "iPhone X"
            },
            {
                "name": "黑色"
            },
            {
                "name": "64g"
            }
        ]
    },
    {
        "spec": [
            {
                "name": "iPhone X"
            },
            {
                "name": "黑色"
            },
            {
                "name": "256g"
            }
        ]
    },
    {
        "spec": [
            {
                "name": "iPhone X"
            },
            {
                "name": "白色"
            },
            {
                "name": "64g"
            }
        ]
    },
    {
        "spec": [
            {
                "name": "iPhone X"
            },
            {
                "name": "白色"
            },
            {
                "name": "256g"
            }
        ]
    },
    {
        "spec": [
            {
                "name": "iPhone XS"
            },
            {
                "name": "黑色"
            },
            {
                "name": "64g"
            }
        ]
    },
    {
        "spec": [
            {
                "name": "iPhone XS"
            },
            {
                "name": "黑色"
            },
            {
                "name": "256g"
            }
        ]
    },
    {
        "spec": [
            {
                "name": "iPhone XS"
            },
            {
                "name": "白色"
            },
            {
                "name": "64g"
            }
        ]
    },
    {
        "spec": [
            {
                "name": "iPhone XS"
            },
            {
                "name": "白色"
            },
            {
                "name": "256g"
            }
        ]
    }
]
回复
1个回答
avatar
test
2024-06-20

let names = ["iPhone X", "iPhone XS"]

let colors = ["黑色", "白色"]

let storages = ["64g", "256g"]

let combine = function (...chunks) {
  let res = []

  let helper = function (chunkIndex, prev) {
    let chunk = chunks[chunkIndex]
    let isLast = chunkIndex === chunks.length - 1
    for (let val of chunk) {
      let cur = prev.concat({name: val})
      if (isLast) {
        // 如果已经处理到数组的最后一项了 则把拼接的结果放入返回值中
        res.push({spec: cur})
      } else {
        helper(chunkIndex + 1, cur)
      }
    }
  }

  // 从属性数组下标为 0 开始处理
  // 并且此时的 prev 是个空数组
  helper(0, [])

  return res
}

console.log(combine(names, colors, storages))
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容