0

I have this object in Javascript.

[{"col1": 1, "col2": 25},{"col1": 1, "col2": 25},{"col1": 3, "col2": 30}]

How can I drop duplicate records in order to get this result?

[{"col1": 1, "col2": 25},{"col1": 3, "col2": 30}]

I have tried next logic, but does not work:

[...new Set(myData)]
Shidersz
  • 16,846
  • 2
  • 23
  • 48
ScalaBoy
  • 3,254
  • 13
  • 46
  • 84
  • https://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript – Robert Jan 14 '19 at 01:39

3 Answers3

1

const a = [{"col1": 1, "col2": 25},{"col1": 1, "col2": 25},{"col1": 3, "col2": 30}];

console.log(
  a.reduce(
    (acc, val) => !acc.some(({col1, col2}) => val.col1 === col1 && val.col2 === col2) 
                  ? acc.concat(val) 
                  : acc, 
     []
  )
);
quirimmo
  • 9,800
  • 3
  • 30
  • 45
1

I recently read this on another answer and I liked it, this uses the optional argument of filter() that is passed as this inside the filter function.

const input = [
    {"col1": 1, "col2": 25},
    {"col1": 1, "col2": 25},
    {"col1": 3, "col2": 30}
];

let res = input.filter(function({col1, col2})
{
    return !this.has(`${col1}-${col2}`) && this.add(`${col1}-${col2}`)
}, new Set());

console.log(res);
Shidersz
  • 16,846
  • 2
  • 23
  • 48
1

This answer shows a simple filter operation with a Set:

const data = [{"col1": 1, "col2": 25},{"col1": 1, "col2": 25},{"col1": 3, "col2": 30}];

const unique = data.filter(function({ col1, col2 }) { return !this.has(`${col1}-${col2}`) && this.add(`${col1}-${col2}`)}, new Set);

console.log(unique);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79