0

data Array

let data = [
{name: "ABC", email: "abc@gamil.com"},
{name: "xyz", email: "xyz@gamil.com"}, 
{name: "different name", email: "abc@gamil.com"}, 
{name: "xyz", email: "cde@gamil.com"}
]

I need result where all objects from an array having same email gets combined into one array as an value and key should be the email. for example the answer of above email should be:

[{
"abc@gmail.com": [
{name: "ABC", email: "abc@gamil.com"},
{name: "different name", email: "abc@gamil.com"}]
},
{"xyz@gamil.com": [
{name: "xyz", email: "xyz@gamil.com"}]
},
{"cde@gamil.com": [
{name: "xyz", email: "cde@gamil.com"}]
}
]

Objective is to get all the duplicate data on the base of email from the available data.

Shakeel
  • 21
  • 7

1 Answers1

2

const data = [
  { name: 'ABC', email: 'abc@gamil.com' },
  { name: 'xyz', email: 'xyz@gamil.com' },
  { name: 'different name', email: 'abc@gamil.com' },
  { name: 'xyz', email: 'cde@gamil.com' },
];
const result = data.reduce((acc, curr) => {
  const key = curr.email;
  if (acc[key]) {
    acc[key].push(curr);
  } else {
    acc[key] = [curr];
  }
  return acc;
}
  , {});
console.log(result);
Parvesh Kumar
  • 1,104
  • 7
  • 16