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

combine array of object if atleast one property is common

//this one is actual array

 const data = [
        {
          name: 'shanu',
          label: 'ak',
          value: 1,
        },
        {
          name: 'shanu',
          label: 'pk',
          value: 2,
        },
        {
          name: 'bhanu',
          label: 'tk',
          value: 3,
        },
      ];
>

//and this  is the array that I want
let outPut =
[
{
name:'shanu',
label:['ak','pk'],
value:[1,2]
},
{
name:'bhanu',
label:['tk'],
value:[3]
}
]

>Solution :

You can use Array.prototype.reduce() like this:

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

const data = [
  {
    name: 'shanu',
    label: 'ak',
    value: 1,
  },
  {
    name: 'shanu',
    label: 'pk',
    value: 2,
  },
  {
    name: 'bhanu',
    label: 'tk',
    value: 3,
  },
];

const output = data.reduce((prev, curr) => {
  const tmp = prev.find((e) => e.name === curr.name)
  if (tmp) {
    tmp.label.push(curr.label)
    tmp.value.push(curr.value)
  } else {
    prev.push({
      name: curr.name,
      label: [curr.label],
      value: [curr.value],
    })
  }
  return prev
}, [])

console.log(output)
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