-1

I have an array of objects which look like below

    let array1 = [
    { 'id': 356, 'name': 'Apple', 'quantity': 150 },
    { 'id': 356, 'name': 'Apple', 'quantity': 200 },
    { 'id': 370, 'name': 'Orange', 'quantity': 200 }

];

I need to sum quantity and return new array if duplicate id is found

Expected result

[
        { 'id': 356, 'name': 'Apple', 'quantity': 350 },
        { 'id': 370, 'name': 'Orange', 'quantity': 200 }

     ]
  • Also: https://stackoverflow.com/questions/19233283/sum-javascript-object-propertya-values-with-same-object-propertyb-in-array-of-ob – Harun Yilmaz Jan 04 '21 at 10:03

1 Answers1

2

 let array1 = [
    { 'id': 356, 'name': 'Apple', 'quantity': 150 },
    { 'id': 356, 'name': 'Apple', 'quantity': 200 },
    { 'id': 370, 'name': 'Orange', 'quantity': 200 }

];

var result = Enumerable.From(array1)
        .GroupBy("$.name", null,
                 function (key, g) {
                     return {
                       name: key,
                       quantity: g.Sum("$.quantity")
                     }
        })
        .ToArray();

console.log(result);
<script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>
Mahesh
  • 137
  • 1
  • 5