0

I have an array of objects with some information. Lines with the same color and size, I want to make a total sum and delete the duplicated lines, that is, for each color and size equal, I only want to get one line.

My object array

  data = [
{
  tam: 'S',
  color: 'blue',
  total: 5
},
{
  tam: 'S',
  color: 'blue',
  total: 10
},
{
  tam: 'S',
  color: 'blue',
  total: 20
},
{
  tam: 'M',
  color: 'blue',
  total: 5
},
{
  tam: 'L',
  color: 'blue',
  total: 5
}

];

The desired output

 data = [
    {
      tam: 'S',
      color: 'blue',
      total: 35
    },
    {
      tam: 'M',
      color: 'blue',
      total: 5
    },
    {
      tam: 'L',
      color: 'blue',
      total: 5
    }
  ];

DEMO

mplungjan
  • 169,008
  • 28
  • 173
  • 236
John w.
  • 511
  • 1
  • 5
  • 18
  • 1
    What did you try here to get your output? – Tushar Shahi Jul 05 '21 at 08:33
  • Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Jul 05 '21 at 08:33
  • So your demo shows the correct result - did you upload the solution from decpk? – mplungjan Jul 05 '21 at 08:46

2 Answers2

1

You could use a reduce fuction to sum elements with same tam attribute. Then a map on result to create the array of object:

data = [
    {
      tam: 'S',
      color: 'blue',
      total: 5
    },
    {
      tam: 'S',
      color: 'blue',
      total: 10
    },
    {
      tam: 'S',
      color: 'blue',
      total: 20
    },
    {
      tam: 'M',
      color: 'blue',
      total: 5
    },
    {
      tam: 'L',
      color: 'blue',
      total: 5
    }
    ];

    var result = data.reduce(function(acc, x) {
      var id = acc[x.tam]
      if (id) {
        id.tam = x.tam
        id.total += x.total
      } else {
        acc[x.tam] = x
      }
      return acc
    },{});
    
    result = Object.keys(result)
    .sort(function(x, y){return +x - +y})
    .map(function(k){return result[k]})

    console.log(result)
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
1

You can use reduce and find to achieve the desired result.

const data = [
  { tam: "S", color: "blue", total: 5 },
  { tam: "S", color: "blue", total: 10 },
  { tam: "S", color: "blue", total: 20 },
  { tam: "M", color: "blue", total: 5 },
  { tam: "L", color: "blue", total: 5 },
];

const result = data.reduce((acc, curr) => {
  const objInAcc = acc.find((o) => o.tam === curr.tam && o.color === curr.color);
  if (objInAcc) objInAcc.total += curr.total;
  else acc.push(curr);
  return acc;
}, []);

console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42