JavaScript / Lodash - 仅保留唯一元素

时间:2018-02-14 13:58:39

标签: javascript lodash

我有一个数组应该只包含其中的唯一元素(当前不存在于数组中的元素),并且只应该将唯一元素推入其中。

数组:

  [{
          "group1": [{
                  "objectId": "lFIlRCwbgY"
              },
              {
                  "objectId": "OjHJ1DlP04"
              },
              {
                  "objectId": "Xasht4pMus"
              },
              {
                  "objectId": "X3qEb8tBtA"
              }
          ]
      },
      {
          "group2": [{
                  "objectId": "rwyACF8j1u"
              },
              {
                  "objectId": "al3Ko6cuUr"
              },
              {
                  "objectId": "VqJMLDDs5W"
              },
              {
                  "objectId": "gIjh41rI0i"
              }
          ]
      },
      {
          "group3": [{
                  "objectId": "X3qEb8tBtA"
              },
              {
                  "objectId": "GRFIMzVxiL"
              },
              {
                  "objectId": "gIjh41rI0i"
              },
              {
                  "objectId": "n6JI6cq7B6"
              }
          ]
      }
  ]

目前,我正在采用以下方式在每个组中拥有唯一ID:

     var restaurantFound = _.some(this.wholeGroup[0].group1, { objectId: el.objectId });

     if (this.wholeGroup[1]) {
      if (restaurantFound == false && this.wholeGroup[1].group2.length < 4) {
        this.wholeGroup[1].group2.push(el.objectId);
      }
    }

问题:

在10%的情况下,具有Id的元素会重复出现,例如在第2组中的元素gIjh41rI0i上面的JSON中重复了第3组。

2 个答案:

答案 0 :(得分:0)

使用您的数据结构并不容易,但似乎我设法自动执行检查和添加项目:

var wholeGroup = [{
  "group1": [{
    "objectId": "lFIlRCwbgY"
  }, {
    "objectId": "OjHJ1DlP04"
  }, {
    "objectId": "Xasht4pMus"
  }, {
    "objectId": "X3qEb8tBtA"
  }]
}, {
  "group2": [{
    "objectId": "rwyACF8j1u"
  }, {
    "objectId": "al3Ko6cuUr"
  }, {
    "objectId": "VqJMLDDs5W"
  }, {
    "objectId": "gIjh41rI0i"
  }]
}, {
  "group3": [{
    "objectId": "X3qEb8tBtA"
  }, {
    "objectId": "GRFIMzVxiL"
  }, {
    "objectId": "gIjh41rI0i"
  }]
}];

var el = {
  objectId: "n6JI6cq7B4"
};
var el2 = {
  objectId: "n6JI6cq7B8"
};

tryAdd(wholeGroup, el);
tryAdd(wholeGroup, el);
tryAdd(wholeGroup, el2);

function tryAdd(wholeGroup, el){
  var list = _.map(wholeGroup, function(obj) { return _.values(obj); });

  var exist = _.some(_.flatten(list), { 'objectId': el.objectId });

  if (!exist) {
    var last = wholeGroup[wholeGroup.length - 1];
    var key = _.keys(last)[0];

    if (last[key].length < 4) {
      last[key].push(el);
      console.log("Add " + el.objectId + " to "+ key);
    } else {
      var number = +key[key.length - 1];
      var newGroup = {};
      var newKey = "group" + (number + 1);
      newGroup[newKey] = [el];
      wholeGroup.push(newGroup);
      console.log("Add " + el.objectId + " to new group "+ newKey);
    }
  }
  else{
    console.log(el.objectId + " already exists");
  }
}
console.log(wholeGroup);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.2.1/lodash.js"></script>

请注意,有很多省略的null / index / exception检查。

答案 1 :(得分:0)

您可以通过展平和使用objectId来获取所有唯一new Set()。然后,您可以将对象分组为4,然后使用array#reduce创建结果。

&#13;
&#13;
var data = [{ "group1": [{ "objectId": "lFIlRCwbgY" }, { "objectId": "OjHJ1DlP04" }, { "objectId": "Xasht4pMus" }, { "objectId": "X3qEb8tBtA" } ] }, { "group2": [{ "objectId": "rwyACF8j1u" }, { "objectId": "al3Ko6cuUr" }, { "objectId": "VqJMLDDs5W" }, { "objectId":"gIjh41rI0i" } ] }, { "group3": [{ "objectId": "X3qEb8tBtA" }, { "objectId": "GRFIMzVxiL" }, { "objectId": "gIjh41rI0i" }, { "objectId": "n6JI6cq7B6" } ] } ],
  result = [...new Set([].concat(...data.map(o => Object.values(o)[0]))
      .map(o => Object.values(o)[0]))]
      .reduce((r,objectId,i) => {
        let index = Math.floor(i/4);
        r[index] = r[index] || [];
        r[index].push({objectId});
        return r;
      },[])
      .reduce((r,a,i) => {
        r.push({['group'+(i+1)] : a});
        return r;
      },[]);
console.log(result);
&#13;
&#13;
&#13;