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,261
  • 2
  • 18
  • 44
ScalaBoy
  • 2,946
  • 10
  • 36
  • 74

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,530
  • 2
  • 27
  • 43
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,261
  • 2
  • 18
  • 44
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
  • 40,575
  • 10
  • 44
  • 74