Home > OS >  Remove duplicates from javascript objects array based on object property value
Remove duplicates from javascript objects array based on object property value

Time:06-19

i want to remove duplicates from javascript 'objects array' based on object property value

  var data = [
    {
      "John Doe": ["[email protected]"],
    },
    {
      "William Smith": ["[email protected]"],
    },
    {
      "Robert Johnson": ["[email protected]", "[email protected]"],
    },
    {
      "John Smith": ["[email protected]", "[email protected]"],
    },
    {
      "James Johnson": ["[email protected]"],
    },
  ];

here in the 'data' array there are same emails for "John Doe" and "John Smith", i want to remove one object of theme.

example:

var data = [
    {
        "John Doe": ["[email protected]"] 
    },
    {
        "William Smith": ["[email protected]"] 
    },
    {
        "Robert Johnson": ["[email protected]", "[email protected]"] 
    },
    {
        "James Johnson": ["[email protected]"] 
    },
];

CodePudding user response:

This can be done with Array.reduce(), combined with Object.values() as follows:

var data = [{
    "John Doe": ["[email protected]"],
  },
  {
    "William Smith": ["[email protected]"],
  },
  {
    "Robert Johnson": ["[email protected]"],
  },
  {
    "John Smith": ["[email protected]"],
  },
  {
    "James Johnson": ["[email protected]"],
  },
];

const result = data.reduce((acc, o) => {
  if (!acc.map(x => Object.values(x)[0][0]).includes(Object.values(o)[0][0])) {
    acc.push(o);
  }
  return acc;
}, []);

console.log(result);

  • Related