Nodejs How to combine specific row if it is redundant?

How to filter out the non-unique values in an array and combine it using javascript?

This is the sample array

[
   {
      "id": 1,
      "CreatedDate": "2022-07-15 16:08",
      "description": "dddd ",
      "section": "Apple"

  },
  {
      "id": 2,
      "CreatedDate": "2022-07-15 16:08",
      "description": "ddd",
      "section": "Apple"
  },
  {
      "id": 3,
      "CreatedDate": "2022-07-15 16:08",
      "name": "aaa",
      "section": "orange"
  }
]

what i want result is

[
   {
      "id": 1,
      "CreatedDate": "2022-07-15 16:08",
      "description": "dddd, ddd",
      "section": "Apple"

  },

  {
      "id": 2,
      "CreatedDate": "2022-07-15 16:08",
      "name": "aaa",
      "section": "orange"
  }
]

How to filter out the non-unique values in an array and combine it using javascript?How to filter out the non-unique values in an array and combine it using javascript?How to filter out the non-unique values in an array and combine it using javascript?

>Solution :

We can do it via Array.reduce()

let data = [
   {
      "id": 1,
      "CreatedDate": "2022-07-15 16:08",
      "description": "dddd ",
      "section": "Apple"

  },
  {
      "id": 2,
      "CreatedDate": "2022-07-15 16:08",
      "description": "ddd",
      "section": "Apple"
  },
  {
      "id": 3,
      "CreatedDate": "2022-07-15 16:08",
      "name": "aaa",
      "section": "orange"
  }
]

let result = data.reduce((a,c) =>{
  let obj = a.find(i => i.section === c.section)
  if(obj){
    obj.description += " / " + c.description
  }else{
    c.id = a.length + 1 // reset the id
    a.push(c) 
  }
  return a
},[])
console.log(result)

Leave a Reply