前端商品sku生成算法,最快速、最方便的生成方式

3,079 阅读1分钟

不喜欢啰嗦,所以中间没内容,直接上例子,简单实用就好。

  • 笛卡尔积算法
      handleCartesianProduct(array = []) {
        if (Object.prototype.toString.call(array) === '[object Array]' && array.length < 2) return [...array[0].map(el => [el])];
        return array.reduce((col, row) => {
          const res = [];
          col.forEach((c) => {
            row.forEach((r) => {
              const t = [].concat(Array.isArray(c) ? c : [c]);
              t.push(r);
              res.push(t);
            });
          });
          return res;
        });
      },
const names    = ['iPhone'];
const color    = ['黑色', '土豪金'];
const storages = ['128g', '256g', '512g'];

const products = [names, color, storages];

handleCartesianProduct(products);

示例如下