在javascript中对数组进行分组

时间:2016-01-25 11:58:18

标签: javascript arrays

我在数组数组中寻找功能组,并写了类似的东西,

var response = {
  "data": {
    "results": {
      "facebook": [
        [
          "Campaign Name",
          'promo',
          'id'
        ],
        [
          "Sok_MPA_10Link_IntOnlineShoppingSites_1412",
          "promo1",
          4
        ],
        [
          "PPLA",
          "promo1",
          9
        ],
        [
          "PPLA",
          "promo2",
          90
        ],
        [
          "Sok_MPA_10Link_IntOnlineShoppingSites_1412",
          "promo1",
          45,
          5
        ]
      ]
    }
  },
  "exception": null,
  "status": "OK",
  "sokratiRequestId": null,
  "json": null
};


var mapData = {};

$.map(response.data.results, function(value, key) {
  headers = value.shift();

  $.map(response.data.results[key], function(data) {
    $.each(headers, function(index, column) {
      if (index == headers.indexOf('id')) return true;

      if (mapData[column] == undefined) {
        mapData[column] = {};
      }
      if (mapData[column][data[index]] == undefined) {
        mapData[column][data[index]] = 0;
      }
      mapData[column][data[index]] += data[headers.indexOf('id')]
    });
  });
  console.log(mapData)
});

基本上我想分组数组中的多个字段 - 比如["广告系列名称" &安培;促销']

实现它的任何好方法?

输出应为 -

"Campaign Name": {
    PPLA: 99
    Sok_MPA_10Link_IntOnlineShoppingSites_1412: 49
},
"promo": {
    promo1: 58
    promo2: 90
}

https://jsfiddle.net/ezg8Lzdr/

注意

答案应该纯粹是在JS中 - 没有其他框架[没有lodash]

5 个答案:

答案 0 :(得分:1)

编辑:

使用Array.prototype.reduce()和结果的对象。给定的groups项是针对组属性及其所需数据部分的索引来获取子属性。

var response = { "data": { "results": { "facebook": [["Campaign Name", 'promo', 'id'], ["Sok_MPA_10Link_IntOnlineShoppingSites_1412", "promo1", 4], ["PPLA", "promo1", 9], ["PPLA", "promo2", 90], ["Sok_MPA_10Link_IntOnlineShoppingSites_1412", "promo1", 45, 5]] } }, "exception": null, "status": "OK", "sokratiRequestId": null, "json": null },
    data = response.data.results.facebook,
    result = {},
    groups = data.shift();

groups.pop();

result = data.reduce(function (r, a) {
    groups.forEach(function (b, i) {
        r[b] = r[b] || {};
        r[b][a[i]] = (r[b][a[i]] || 0) + a[2];
    });
    return r;
}, {});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

答案 1 :(得分:0)

我在JS上写了一个可以帮助你的小函数:

function groupBy(collection, property) {

var i = 0, val, index,
    values = [], result = [];
for (; i < collection.length; i++) {
    val = collection[i][property];
    index = values.indexOf(val);
    if (index > -1)
        result[index].push(collection[i]);
    else {
        values.push(val);
        result.push([collection[i]]);
    }
}
return result;

};

使用很简单:

groupBy(myArray, "facebook");

答案 2 :(得分:0)

如果数据模式已经修复了很多:

var response = {
  "data": {
    "results": {
      "facebook": [
        [
          "Campaign Name",
          'promo',
          'id'
        ],
        [
          "Sok_MPA_10Link_IntOnlineShoppingSites_1412",
          "promo1",
          4
        ],
        [
          "PPLA",
          "promo1",
          9
        ],
        [
          "PPLA",
          "promo2",
          90
        ],
        [
          "Sok_MPA_10Link_IntOnlineShoppingSites_1412",
          "promo1",
          45,
          5
        ]
      ]
    }
  },
  "exception": null,
  "status": "OK",
  "sokratiRequestId": null,
  "json": null
};

var face = response.data.results.facebook;

//remove first row which is a schema
face.shift();

//take in index of column, return grouped sum
var reduce = function(index) {
  return face.reduce((t, a) => {
    t[a[index]] = (t[a[index]] || 0) + a[2];
    return t;
  }, {});
}

//final result
var result = {
  "Campaign Name": reduce(0),
  "promo": reduce(1)
}
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

答案 3 :(得分:-1)

对于数组,集合或JavaScript中的任何基本操作,我建议使用像 lodash 这样的框架,这些框架充满了你在项目中需要的所有技巧:

https://lodash.com/docs#groupBy

答案 4 :(得分:-1)

最常见的方法是使用库进行数据操作,例如https://lodash.com/

使用此库,您可以对数据进行分组:

var result = _.chain(data)
    .groupBy("color")
    .pairs()
    .map(function(currentItem) {
        return _.object(_.zip(["color", "users"], currentItem));
    })
    .value();