'Get all objects in an array for same property value from an array of data [duplicate]

data Array

let data = [
{name: "ABC", email: "[email protected]"},
{name: "xyz", email: "[email protected]"}, 
{name: "different name", email: "[email protected]"}, 
{name: "xyz", email: "[email protected]"}
]

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:

[{
"[email protected]": [
{name: "ABC", email: "[email protected]"},
{name: "different name", email: "[email protected]"}]
},
{"[email protected]": [
{name: "xyz", email: "[email protected]"}]
},
{"[email protected]": [
{name: "xyz", email: "[email protected]"}]
}
]

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



Solution 1:[1]

const data = [
  { name: 'ABC', email: '[email protected]' },
  { name: 'xyz', email: '[email protected]' },
  { name: 'different name', email: '[email protected]' },
  { name: 'xyz', email: '[email protected]' },
];
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);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Parvesh Kumar