Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
   {
      "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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading