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 to concat duplicates from an array of objects and delete one of them

I am trying to check if in an array of objects I have duplicates date, then I have to concat the duplicate obj with name and remove one of them.

This is what I could do:

var arr = [
    {name: "Adam", date: "25/11/2022" },
    {name: "Jorge", date: "25/11/2022" },
    {name: "Lucas", date: "24/11/2022" },
    {name: "Bob", date: "23/11/2022" }
]

function getUniqueListBy(arr, key) {
    return [...new Map(arr.map(item => [item[key], item])).values()]
}

const arr1 = getUniqueListBy(arr, 'date')
console.log(JSON.stringify(arr1))

What I need is this result:

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

var arr1 = [{"name":"Adam / Jorge","date":"25/11/2022"},{"name":"Lucas","date":"24/11/2022"},{"name":"Bob","date":"23/11/2022"}]

So the object with duplicated date would be like this:

{"name":"Adam / Jorge","date":"25/11/2022"}

Any suggestion ?

>Solution :

Try like this:

const arr = [
  { name: "Adam", date: "25/11/2022" },
  { name: "Jorge", date: "25/11/2022" },
  { name: "Lucas", date: "24/11/2022" },
  { name: "Bob", date: "23/11/2022" },
];

const result = Object.entries(
  arr.reduce((prev, { date, name }) => {
    prev[date] = prev[date] ? prev[date] + " / " + name : name;
    return prev;
  }, {})
).map(([date, name]) => ({ name, date }));

console.log(result);

Using Object.entries(), Array.prototype.reduce(), and Array.prototype.map()

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