0

I need to understand the simplest way of doing this. I've got an array of objects:

const data =
[
    {
        "_id": "63613c9d1298c1c70e4be684",
        "NameFood": "Coca",
        "count": 2
    },
    {
        "_id": "63621f10b61f259b13cafe8e",
        "NameFood": "Xa xi",
        "count": 2,
    },
    {
        "_id": "63654bf94b61091ae9c4bfd3",
        "NameFood": "Cafe đen",
        "count": 2,
    },
    {
        "count": 1,
        "_id": "63613c9d1298c1c70e4be684",
        "NameFood": "Coca",
    }
]

I expect the result: filter duplicate values by _Id and plus 'count'

const data =
[
    {
        "_id": "63613c9d1298c1c70e4be684",
        "NameFood": "Coca",
        "count": 3
    },
    {
        "_id": "63621f10b61f259b13cafe8e",
        "NameFood": "Xa xi",
        "count": 2,
    },
    {
        "_id": "63654bf94b61091ae9c4bfd3",
        "NameFood": "Cafe đen",
        "count": 2,
    },
]

Can anybody explain it to me step by step, please?

  • Can you post what you've tried? – JoshG Nov 06 '22 at 07:16
  • I don't know how to get the above output? – Hoàng -mp Nov 06 '22 at 07:18
  • Get familiar with [how to access and process objects, arrays, or JSON](/q/11922383/4642212), how to [access properties](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_Accessors), and how to create [objects](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer), and use the static and instance methods of [`Object`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Nov 06 '22 at 07:20
  • [Duplicate](//google.com/search?q=site:stackoverflow.com+js+remove+duplicates+and+sum) of [Sum similar keys in an array of objects](/q/24444738/4642212). – Sebastian Simon Nov 06 '22 at 07:21
  • 1
    I suggest to read the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) - and to learn all the other methods in the left column. At least their names. – Roko C. Buljan Nov 06 '22 at 07:23

1 Answers1

0

Just using reduce() can do it

const data =
[
    {
        "_id": "63613c9d1298c1c70e4be684",
        "NameFood": "Coca",
        "count": 2
    },
    {
        "_id": "63621f10b61f259b13cafe8e",
        "NameFood": "Xa xi",
        "count": 2,
    },
    {
        "_id": "63654bf94b61091ae9c4bfd3",
        "NameFood": "Cafe đen",
        "count": 2,
    },
    {
        "count": 1,
        "_id": "63613c9d1298c1c70e4be684",
        "NameFood": "Coca",
    }
]

let result = data.reduce((a,c) =>{
  let obj = a.find(i => i._id == c._id)
  if(obj){
     obj.count += c.count 
   }else{
     a.push(c)
   }
  return a
},[])
console.log(result)
flyingfox
  • 13,414
  • 3
  • 24
  • 39