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

How do I extract duplicate values for objects in JavaScript?

I have the data from the database and I want to push the duplicate value to each array. I attach the exact example I want.

        // origin data
        const data = [
            {
                name: "Amy",
                age: 17,
            },
            {
                name: "Amy",
                age: 17,
            },
            {
                name: "Amy",
                age: 17,
            },
            {
                name: "Tommy",
                age: 20,
            },
            {
                name: "Tommy",
                age: 20,
            },
        ];

        //result that I want to get
        arr1 = [
            {
                name: "Amy",
                age: 17,
            },
            {
                name: "Amy",
                age: 17,
            },
            {
                name: "Amy",
                age: 17,
            },
        ];
        arr2 = [
            {
                name: "Tommy",
                age: 20,
            },
            {
                name: "Tommy",
                age: 20,
            },
        ];

I want to create an array based on the name in this data and push it. Can anyone help?

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

>Solution :

One way would be to use reduce together with Object.values:

const data = [
  {
    name: "Amy",
    age: 17,
  },
  {
    name: "Amy",
    age: 17,
  },
  {
    name: "Amy",
    age: 17,
  },
  {
    name: "Tommy",
    age: 20,
  },
  {
    name: "Tommy",
    age: 20,
  }
];

const result = Object.values(data.reduce((acc, cur) => {
  const key = `${cur.name}:${cur.age}`;
    const prev = acc[key] || [];
  return {
    ...acc,
    [key]: prev.concat(cur)
  }
}, {}));

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