-2

I need to get an array by combining objects with the same type - adding their weight ․․․

const arr = [ {type: "a", weight: 10}, {type: "b", weight: 15}, {type: "a", weight: 20},]
    

Expected result;

  [ {type: "a", weight: 30}, {type: "b", weight: 15},]
Irfan wani
  • 4,084
  • 2
  • 19
  • 34
Yervand
  • 99
  • 1
  • 1
  • 4
  • Please provide an example of what you have tried and its outcomes first. SO is intended to help with errors and difficulties you face in your code so concepts can be clarified and explained, not to do your work for you – Karan Shishoo Mar 02 '21 at 12:17
  • You can achieve this by using the array method `Array.reduce()`. Try it yourself and come back here if you are encountering problems. – Nicolae Maties Mar 02 '21 at 12:32
  • Here is the answer that you expect https://stackoverflow.com/a/57477448/7785337 .. Anyhow for your code you need to modify only the key names.. And the working example here: https://codepen.io/Maniraj_Murugan/pen/MWbGXNV – Maniraj Murugan Mar 02 '21 at 12:37
  • 1
    Does this answer your question? [how to group by and sum array of object?](https://stackoverflow.com/questions/29364262/how-to-group-by-and-sum-array-of-object) – pilchard Mar 02 '21 at 12:45

1 Answers1

-1

Here you go! Please comment if you need explanation as the code just uses for loop

    const arr = [ {type: "a", weight: 10}, {type: "b", weight: 15}, {type: "a", weight: 20},]
    
    
    for(let i = 0; i < arr.length; i++) {
        for(let j = i + 1; j < arr.length; j++) {
            if(arr[i].type == arr[j].type) {
                arr[i].weight =  arr[i].weight + arr[j].weight;
                arr.splice(j, 1)
            }
        }
    }

    console.log(arr)
Irfan wani
  • 4,084
  • 2
  • 19
  • 34
  • 2
    This is a duplicate question with multiple solutions already available so please just flag. Also there is no need for a nested loop. – pilchard Mar 02 '21 at 12:49