在javascript中分组和汇总哈希数组

时间:2018-02-19 13:07:04

标签: javascript

我有以下哈希数组,并希望将其转换为类似帖子底部的数组。



var responseData = [
  {deviceType: "Smartphone", deviceCount: 14},
  {deviceType: "Tablet", deviceCount: 11},
  {deviceType: "Notebook", deviceCount: 3},
  {deviceType: "Desktop", deviceCount: 2},
  {deviceType: "Smartphone", deviceCount: 1},
  {deviceType: "Tablet", deviceCount: 10},
  {deviceType: "Notebook", deviceCount: 30},
  {deviceType: "Desktop", deviceCount: 20}
];

function dataMapper(responseData){
  let series = [];
  if(responseData && responseData.length){
  responseData.forEach(function(resource){
  existingElement = series.filter(function (item) {
      return item.deviceType === resource.deviceType;
    });
  if (existingElement) {
    deviceCount = existingElement[0].deviceCount + resource.deviceCount;
    existingElement[0].deviceCount = deviceCount
  }else{
    series[0].push({deviceType: resource.deviceType, y: resource.deviceCount});
  }
    });
  }
  return series
}

console.log(dataMapper(responseData))




我想将其转换为:

var expectedResult = [
    {deviceType: "Smartphone", deviceCount: 15},
    {deviceType: "Tablet", deviceCount: 21},
    {deviceType: "Notebook", deviceCount: 33},
    {deviceType: "Desktop", deviceCount: 22}
];

8 个答案:

答案 0 :(得分:4)

使用ES6地图和reduce

const responseData = [{deviceType: "Smartphone", deviceCount: 14},{deviceType: "Tablet", deviceCount: 11},{deviceType: "Notebook", deviceCount: 3},{deviceType: "Desktop", deviceCount: 2},{deviceType: "Smartphone", deviceCount: 1},{deviceType: "Tablet", deviceCount: 10},{deviceType: "Notebook", deviceCount: 30},{deviceType: "Desktop", deviceCount: 20}];

const result = Array.from(
    responseData.reduce( 
        (acc, o) => (acc.get(o.deviceType).deviceCount += o.deviceCount, acc),
        new Map(responseData.map( ({deviceType}) => [deviceType, {deviceType, deviceCount: 0} ] )) 
    ).values()
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:2)

如果您使用哈希表并以并行方式构建结果,则会更容易:

 const hash = {}, result = [];

for(const {deviceType, deviceCount} of responseData){
  if(hash[deviceType]){
     hash[deviceType].deviceCount += deviceCount;
  } else {
     result.push(hash[deviceType] = {deviceType, deviceCount});
  }
}

如果你真的想迭代数组,你应该使用find而不是filter

const result = [];

for(const {deviceType, deviceCount} of responseData){
  const exists = result.find(device => device.deviceType === deviceType);
 if(exists){
   exists.deviceCount += deviceCount;
  } else {
   result.push({deviceType, deviceCount });
  }
}

答案 2 :(得分:2)

您可以将哈希表作为对计数对象的引用,并使用对象返回数组。

var responseData = [{ deviceType: "Smartphone", deviceCount: 14 }, { deviceType: "Tablet", deviceCount: 11 }, { deviceType: "Notebook", deviceCount: 3 }, { deviceType: "Desktop", deviceCount: 2 }, { deviceType: "Smartphone", deviceCount: 1 }, { deviceType: "Tablet", deviceCount: 10 }, { deviceType: "Notebook", deviceCount: 30 }, { deviceType: "Desktop", deviceCount: 20 }],
    hash = Object.create(null),
    result = responseData.reduce(function (r, o) {
        if (!hash[o.deviceType]) {
            hash[o.deviceType] = { deviceType: o.deviceType, deviceCount: 0 };
            r.push(hash[o.deviceType]);
        }
        hash[o.deviceType].deviceCount += o.deviceCount;
        return r;
    }, []);

console.log(result);

另一个解决方案可能是使用Map并稍后获取所有计数设备的数组。

var responseData = [{ deviceType: "Smartphone", deviceCount: 14 }, { deviceType: "Tablet", deviceCount: 11 }, { deviceType: "Notebook", deviceCount: 3 }, { deviceType: "Desktop", deviceCount: 2 }, { deviceType: "Smartphone", deviceCount: 1 }, { deviceType: "Tablet", deviceCount: 10 }, { deviceType: "Notebook", deviceCount: 30 }, { deviceType: "Desktop", deviceCount: 20 }],
    result = Array.from(
        responseData.reduce((map, { deviceType, deviceCount }) => map.set(deviceType, (map.get(deviceType) || 0) + deviceCount), new Map),
        ([ deviceType, deviceCount ]) => ({ deviceType, deviceCount })
    );

console.log(result);

答案 3 :(得分:0)

我们带来预期结果的方法之一是这样做:

var responseData = [{
        deviceType: "Smartphone",
        deviceCount: 14
      },
      {
        deviceType: "Tablet",
        deviceCount: 11
      },
      {
        deviceType: "Notebook",
        deviceCount: 3
      },
      {
        deviceType: "Desktop",
        deviceCount: 2
      },
      {
        deviceType: "Smartphone",
        deviceCount: 1
      },
      {
        deviceType: "Tablet",
        deviceCount: 10
      },
      {
        deviceType: "Notebook",
        deviceCount: 30
      },
      {
        deviceType: "Desktop",
        deviceCount: 20
      }
    ];
    var pushedType = [];
    var summedData = [];

    for (var i in responseData) {
      if (pushedType.indexOf(responseData[i].deviceType) === -1) {
        summedData.push(responseData[i]);
        pushedType.push(responseData[i].deviceType);
      } else {
        summedData[pushedType.indexOf(responseData[i].deviceType)].deviceCount += responseData[i].deviceCount;
        }
      }

      $(".result").html(JSON.stringify(summedData))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result"></div>

希望它可以帮助你:)

答案 4 :(得分:0)

我建议使用Kotti source code

let transformObj = {};
   responseData.reduce((prev,cur) =>{
      const key = cur.deviceType;
      if(!prev[key]){
         prev[key] =  0;
      }
      prev[key] += cur.deviceCount;

      return prev;
   },transformObj);

  const results = Object.keys(transformObj).map(key => {
      return {
           deviceType: key,
           deviceCount: transformObj[key]
      }
  });

let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyyMMdd'T'HHmmssZ" print(dateFormatter.date(from: dateString)) //2018-02-07 12:46:00 +0000

{{1}}

答案 5 :(得分:0)

我为你添加了这个小提琴:https://jsfiddle.net/6zuux7jq/6/

&#13;
&#13;
var responseData = [
  {deviceType: "Smartphone", deviceCount: 14},
  {deviceType: "Tablet", deviceCount: 11},
  {deviceType: "Notebook", deviceCount: 3},
  {deviceType: "Desktop", deviceCount: 2},
  {deviceType: "Smartphone", deviceCount: 1},
  {deviceType: "Tablet", deviceCount: 10},
  {deviceType: "Notebook", deviceCount: 30},
  {deviceType: "Desktop", deviceCount: 20}
];
 
function dataMapper(responseData){
  var series = {};
  if(responseData && responseData.length){
  responseData.forEach(function(element){
       series[element.deviceType] = Number.isInteger(series[element.deviceType]) ? series[element.deviceType] + element.deviceCount : element.deviceCount
    });
  }
  var tmp = []
  for (var i in series) {
    tmp.push({deviceType: i, deviceCount: series[i]})
  }
  return tmp
}

console.log(dataMapper(responseData))
&#13;
&#13;
&#13;

问候

答案 6 :(得分:0)

试试这个

const results = []
var temp = {};

responseData.map(function(item){
    temp[item.deviceType] = (temp[item.deviceType] || 0) + item.deviceCount;;
})

Object.keys(temp).forEach(function(key) {
    results.push({ deviceType: key, deviceCount: temp[key]});
})

console.log(results);

答案 7 :(得分:0)

这是我的解决方案:

set