var players = [{id: 17, amount: 126},
{id: 17, amount: 45},
{id: 12, amount: 44},
{id: 12, amount: 23}];
如何将上面的数组转换为新数组,为每个id添加数量。
var newArray=[{id:17.amount:171},{id:12,amount:67}];
答案 0 :(得分:4)
您可以使用哈希表对相同的ID进行分组,并在必要时添加数量。
from PIL import Image
a = Image.open('img')
a = a.filter(MOTION_BLUR)
基本上这一行
var players = [{ id: 17, amount: 126 }, { id: 17, amount: 45 }, { id: 12, amount: 44 }, { id: 12, amount: 23 }],
grouped = players.reduce(function (hash) {
return function (r, a) {
(hash[a.id] = hash[a.id] || r[r.push({ id: a.id, amount: 0 }) - 1]).amount += a.amount;
return r;
};
}(Object.create(null)), []);
console.log(grouped);
检查(hash[a.id] = hash[a.id] || r[r.push({ id: a.id, amount: 0 }) - 1]).amount += a.amount;
是否存在,如果不存在,那么这部分
hash[a.id]
是perfoming,它包含两部分,一部分用于访问结果集,在内部它将一个新的objetc集推送到结果集。虽然r[r.push({ id: a.id, amount: 0 }) - 1]
返回数组的新长度,但它需要减小索引以获取最后插入的元素。
push
之后,取属性r[ - 1]
r.push({ id: a.id, amount: 0 })
并增加实际元素的数量。
答案 1 :(得分:0)
您还可以稍微更改输出格式,以便更轻松地进行搜索:
var players = [{ id: 17, amount: 126 }, { id: 17, amount: 45 }, { id: 12, amount: 44 }, { id: 12, amount: 23 }],
result = {};
for(var i = 0; i < players.length; i++){
result[players[i].id] =
(result[players[i].id] || 0) + // The existing amount, or 0 for a new `id`
players[i].amount; // Add the current amount
}
console.log(result);
console.log('Amount for 17: ' + result[17]);
这样,您无需在id
值上过滤结果,即可获得金额。
答案 2 :(得分:0)
如果id为new,你可以在一个新数组中推送元素,或者如果它已经存在,只需将数量添加到前一个数组:
var players = [{ id: 17, amount: 126 }, { id: 12, amount: 103 }, { id: 17, amount: 45 }, { id: 12, amount: 44 }, { id: 12, amount: 23 }];
var results = [];
results.push(players.sort((a,b) => a.id-b.id)[0]);
var shift = 0;
players.forEach((item, index, arr) => {
if (index < arr.length - 1){
if (item.id === arr[index+1].id) {
results[index + shift].amount += arr[index+1].amount;
shift--;
}
else results.push(players[index+1]);
}
});
console.log(results); // [ { id: 12, amount: 170 }, { id: 17, amount: 171 } ]