Home > Enterprise >  How do I extract duplicate values for objects in JavaScript?
How do I extract duplicate values for objects in JavaScript?

Time:04-20

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?

CodePudding user response:

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);

  • Related