Home > Enterprise >  How to concat duplicates from an array of objects and delete one of them
How to concat duplicates from an array of objects and delete one of them

Time:11-28

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:

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 ?

CodePudding user response:

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

CodePudding user response:

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" }
];

const grouped = {};
arr.forEach(({name, date}) =>
  (grouped[date] || (grouped[date] = [])).push(name)
);

const result = {};
Object.entries(grouped).forEach(([date, names]) =>
  result[names.join(' / ')] = date
);

console.log(result);

  • Related