将大数组排序为更简单的数组

时间:2018-05-14 14:57:35

标签: javascript arrays ecmascript-6

将myarr排序为sortedArr以便使用javascript为每个invidual id添加所有值的最佳方法是什么?

myarr = [{id: 10, val:100}, {id:10, val: 100}, {id:20, val:200}, {id:20, val:100}, {id:30, val:100}]

sortedArr = [{id: 10, val: 200}, {id:20, val:300}, {id:30, 100}]

4 个答案:

答案 0 :(得分:1)

首先将每个ID的值相加,然后将它们推送到新数组。

let myarr = [{ id: 10, val: 100 }, { id: 10, val: 100 }, { id: 20, val: 200 }, { id: 20, val: 100 }, { id: 30, val: 100 }]
let group = {}

myarr.forEach((value, index) => {
    if (group[value.id]) {
        group[value.id] += value.val
    }
    else {
        group[value.id] = value.val
    }
})

let res = []

Object.keys(group).forEach((key) => {
    res.push({ id: key, val: group[key] })
})

console.log(res);

答案 1 :(得分:0)

您需要保留键(点击)地图并减少原始数组。您可以在之后对其进行排序,因为数组会更小,从而加快排序速度。

var myArr = [{id: 10, val:100}, {id:10, val: 100}, {id:20, val:200}, {id:20, val:100}, {id:30, val:100}];
var sortedArr = accumulateAndSortById(myArr, 'id', 'val');

console.log(sortedArr);

function accumulateAndSortById(arr, field, value) {
  var hitMap = arr.reduce((result, item) => {
    result[item[field]] = (result[item[field]] || 0) + item[value];
    return result;
  }, {});
  return Object.keys(hitMap).reduce((result, key) => {
    var obj = {};
    obj[key] = hitMap[key];
    result.push(obj);
    return result;
  }, []).sort((a, b) => a[field] > b[field]);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

答案 2 :(得分:0)

你可以这样做:

const myArr = [{id: 10, val:100}, {id:10, val: 100}, {id:20, val:200}, {id:20, val:100}, {id:30, val:100}]
const temp = myArr.reduce((a, c) => (a[c.id] = (a[c.id] || 0) + c.val, a), {});
const sortedArr = Object.keys(temp).map(k => ({id: +k, val: temp[k]}));

console.log(sortedArr);

答案 3 :(得分:-2)

使用以下比较功能进行排序:

      var myArr =  [{id: 10, val:100}, {id:10, val: 100}, {id:20, val:200}, {id:20, val:100}, {id:30, val:100}];

  function compare(a,b) {
  if (a.id < b.id)
    return -1;
  if (a.id > b.id)
    return 1;
  return 0;
}

var sortedArr  = myArr.sort(compare);