There is such an array:

[{ id: 100, chance: 10 }, { id: 100, chance: 30 }, { id: 200, chance: 10 }, { id: 300, chance: 5 }, { id: 200, chance: 30 }, { id: 100, chance: 15 } ] 

How to make a loop so that it returns like this:

 id:100 chance: 55 (10+30+15 выводить не надо) id:200 chance: 40 (10+30 выводить не надо) id:300 chance: 5 

It is necessary for the cycle to add chance for objects with the same id

    2 answers 2

    Grouping by id using the object and displaying id + chance :

     var data = [{ id: 100, chance: 10 }, { id: 100, chance: 30 }, { id: 200, chance: 10 }, { id: 300, chance: 5 }, { id: 200, chance: 30 }, { id: 100, chance: 15 }]; var result = {}; for (var element of data) { if (result[element.id] == undefined) result[element.id] = 0; result[element.id] += element.chance; } for (var id in result) console.log("id: " + id + ", chance: " + result[id]); 

    The reduce variant, however, is fundamentally no different from the Regent answer.

     let data = [{ id: 100, chance: 10 }, { id: 100, chance: 30 }, { id: 200, chance: 10 }, { id: 300, chance: 5 }, { id: 200, chance: 30 }, { id: 100, chance: 15 } ]; let result = data.reduce((prev, item) => { if (item.id in prev) { prev[item.id] += item.chance } else { prev[item.id] = item.chance; } return prev; }, {}) Object.keys(result).forEach(id => { console.log(`id:${id}, chance:${result[id]}`); })