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)]
1

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

1 Comment

That's a nice way to use the second argument of fitler().
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, 
     []
  )
);

1 Comment

This would be the first option on my mind, so +1 for you!
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);

2 Comments

And just hope you don't have data like: {"col1": 12, "col2": 3},{"col1": 1, "col2": 23},?
Fixed @MarkMeyer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.