-1
var a = [{3.1: 3.2},
{3.1: 3.2},
{3.1: 3.4},
 {2.8: 3},
 {3.1: 3.2},
 {2.8: 2.8},
 {3.1: 3.4},
 {3.1: 3.2},
 {2.6: 2.6},
 {3.1: 3.2},
  {2.6: 2.6}]

How to drop duplicate object from list of objects. I worked out for this question :- How to remove all duplicates from an array of objects? but could fit to my code.

I am looking for:

[{3.1: 3.2},{3.1: 3.4},{2.8: 3},{2.8: 2.8},{2.6: 2.6},]
Adi
  • 1
  • 6

3 Answers3

0

    var a = [{3.1: 3.2},
    {3.1: 3.2},
    {3.1: 3.4},
     {2.8: 3},
     {3.1: 3.2},
     {2.8: 2.8},
     {3.1: 3.4},
     {3.1: 3.2},
     {2.6: 2.6},
     {3.1: 3.2},
      {2.6: 2.6}]
      
    var k = 
      a.map(aa => JSON.stringify(aa))
       .filter((v, i, s) => s.indexOf(v) === i)
       .map(aa => JSON.parse(aa));
       
    console.log(k)

Object.defineProperty(Array.prototype, "then", {
    value: function then(f) {
        return f(this)
    },
    writable: true,
    configurable: true
});

var a = [{3.1: 3.2},
        {3.1: 3.2},
        {3.1: 3.4},
         {2.8: 3},
         {3.1: 3.2},
         {2.8: 2.8},
         {3.1: 3.4},
         {3.1: 3.2},
         {2.6: 2.6},
         {3.1: 3.2},
          {2.6: 2.6}]
          
          
        var k = 
          a.map(aa => JSON.stringify(aa))
           .then(data => [...new Set(data)])
           .map(aa => JSON.parse(aa));
           
        console.log(k)
Nafis Islam
  • 1,483
  • 1
  • 14
  • 34
0

You could filter with a Set.

const
    array = [{ 3.1: 3.2 }, { 3.1: 3.2 }, { 3.1: 3.4 }, { 2.8: 3 }, {  3.1: 3.2 }, { 2.8: 2.8 }, { 3.1: 3.4 }, { 3.1: 3.2 }, { 2.6: 2.6 }, { 3.1: 3.2 }, { 2.6: 2.6 }],
    unique = array.filter(
        (s => o => 
            (j => !s.has(j) && s.add(j))
            (JSON.stringify(o))
        )
        (new Set)
    );

console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can easily achieve this as follows

  • Create pairs from the object
  • Filter the duplicates
  • create object again from filtered objects

var a = [
  { 3.1: 3.2 },
  { 3.1: 3.2 },
  { 3.1: 3.4 },
  { 2.8: 3 },
  { 3.1: 3.2 },
  { 2.8: 2.8 },
  { 3.1: 3.4 },
  { 3.1: 3.2 },
  { 2.6: 2.6 },
  { 3.1: 3.2 },
  { 2.6: 2.6 },
];

const keyValuePairs = a.map((obj) => {
  const [[key, value]] = Object.entries(obj);
  return `${key}|${value}`;
});

const filteredResult = [...new Set(keyValuePairs)];
const result = filteredResult.map((s) => {
  const [key, value] = s.split("|");
  return { [key]: value };
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
DecPK
  • 24,537
  • 6
  • 26
  • 42