Get all possible options for a matrix in javascript

前端 未结 4 2032
后悔当初
后悔当初 2021-01-02 15:32

I have an \'item\' object in JavaScript, and the item can have settings like color, size, etc.

I need to get all possible combinations in an array.

So lets s

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-02 16:21

    You can use Array.prototype.map(), for loop, while loop, Array.prototype.concat(). Iterate gender values; select each of color, size value in succession beginning at index 0 of either; iterating the furthest adjacent array from current gender, increment the index of the closest adjacent array; merge the resulting two gender arrays to form a single array containing all combinations of gender, color, size

    var colors = newItem.Settings[0].values;
    var sizes = newItem.Settings[1].values;
    var gen = newItem.Settings[2].values;
    var i = sizes.length;
    
    var res = [].concat.apply([], gen.map(function(value, key) {
      var next = -1;
      var arr = [];
      for (var curr = 0; curr < i; curr++) {
        while (next < i - 1) {
          arr.push([{
            SettingName: "gender",
            value: value
          }, {
            SettingName: "size",
            value: sizes[curr]
          }, {
            SettingName: "color",
            value: colors[++next]
          }])
        }
        next = -1;
      }
      return arr
    }))
    

    var newItem = {
      "name": "new item",
      "Settings": [{
        "name": "color",
        "values": [
          "green",
          "blue",
          "red"
        ]
      }, {
        "name": "size",
        "values": [
          "15",
          "18",
          "22"
        ]
      }, {
        "name": "gender",
        "values": [
          "male",
          "female"
        ]
      }]
    }
    
    var colors = newItem.Settings[0].values;
    var sizes = newItem.Settings[1].values;
    var gen = newItem.Settings[2].values;
    var i = sizes.length;
    
    var res = [].concat.apply([], gen.map(function(value, key) {
      var next = -1;
      var arr = [];
      for (var curr = 0; curr < i; curr++) {
        while (next < i - 1) {
          arr.push([{
            SettingName: "gender",
            value: value
          }, {
            SettingName: "size",
            value: sizes[curr]
          }, {
            SettingName: "color",
            value: colors[++next]
          }])
        }
        next = -1;
      }
      return arr
    }))
    
    document.querySelector("pre").textContent = JSON.stringify(res, null, 2)

    plnkr http://plnkr.co/edit/C2fOJpfwOrlBwHLQ2izh?p=preview

提交回复
热议问题