如何在javascript数组中推送重复值后消除重复值

时间:2018-03-17 06:01:51

标签: javascript amcharts

我想删除chartDataResults2数组中状态的重复值:

for (i = 0; i < dataResults.length; i++) {
  function groupBy(array, f) {
    var groups = {};
    array.forEach(function(o) {
      var group = JSON.stringify(f(o));
      groups[group] = groups[group] || [];
      groups[group].push(o);
    });
    return Object.keys(groups).map(function(group) {
      return groups[group];
    })
  }

  var result = groupBy(dataResults, function(item) {
    return [item.State.Title];
  });

  States1 = result[i][0].State.Title;

  chartDataResults2.push({
    States: States1,
    Mineraltype: Mineraltype,
    CollectionAmount: CollectionAmount,
    Major: major,
    Minor: minor,
    CoalLignite: coal,
    balloonTextField: Mineraltype + ", Total Amount Collected:" + CollectionAmount,

  });
}

各州都有价值观(安得拉邦,古吉拉特邦,古吉拉特邦)。它应该删除重复并保留(安得拉邦的安得拉邦)。

{States: "ANDHRA PRADESH", CollectionAmount: 187, Major: 187, Minor: 0, …}

{States: "GUJARAT",  CollectionAmount: 301, Major: 158, Minor: 90, …}

{States: "GUJARAT",  CollectionAmount: 0, Major: 0, Minor: 0, …}

2 个答案:

答案 0 :(得分:0)

您可以使用States根据对象中的var data = [{States: "ANDHRA PRADESH", CollectionAmount: 187, Major: 187, Minor: 0},{States: "GUJARAT", CollectionAmount: 301, Major: 158, Minor: 90},{States: "GUJARAT", CollectionAmount: 0, Major: 0, Minor: 0}]; var result = Object.values(data.reduce((r,o) => { r[o.States] = r[o.States] || {...o}; return r; },{})); console.log(result);值对数据进行分组。然后从对象中提取出所有值。

var json_all = [{States: "ANDHRA PRADESH", CollectionAmount: 187, Major: 187, Minor: 0, …},{States: "GUJARAT",  CollectionAmount: 301, Major: 158, Minor: 90, …},{States: "GUJARAT",  CollectionAmount: 0, Major: 0, Minor: 0, …}];
var arr = [],
    collection = [];

$.each(json_all, function (index, value) {
    if ($.inArray(value.id, arr) == -1) {
        arr.push(value.id);
        collection.push(value);
    }
});

答案 1 :(得分:0)

generic_map

试试这种方式