0

I have an array of objects in my TypeScript-code and I need to get out the duplicate ones. The following code does the work for me:

 const uniqueObjects = Array.from(new Set(nonUniqueObjects.map((x) => {
        return JSON.stringify(x);
      }))).map((y) => JSON.parse(y));

The problem is when I run the code I get an error from Awesome TypeScript loader which is the following

Argument of type '{}' is not assignable to parameter of type 'string'.

The code which it doesn't probably like is the .map((y) => JSON.parse(y));

I also want to achieve this without using var or let, only const.

3 Answers 3

1

Try with the spread operator :

let nonUniqueObjects = [{a : 1} , {b : 2}, {a : 1}, {b : 2}, {c : 3}]

const uniqueObjects = [...new Set(nonUniqueObjects.map( x => JSON.stringify(x)))]
		     .map( y => JSON.parse(y) )

console.log(uniqueObjects)

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

1 Comment

Still getting the same error. I'm pretty sure it has something to do with TypeScript, since this works perfectly in javascript
1

Found the solution. The problem was with

.map((y) => JSON.parse(y));

My TypeScript compiler didn't seem to like that 'y' wasn't a string, even though it made it into a string. So I solved it by calling toString().

.map((y) => JSON.parse(y.toString()));

The complete solution for removing non-unique Objects in an array:

  const uniqueObjects = Array.from(new Set(nonUniqueObjects.map((x) => JSON.stringify(x)))).map((y) => JSON.parse(y.toString()));

Probably still need to do some error handling, but that's a different story.

Comments

0

Here,

var nonUniqueObjects = [{
  'id': 1,
  'name': 'A'
}, {
  'id': 2,
  'name': 'B'
}, {
  'id': 1,
  'name': 'A'
}];

var uniqueObjects = new Set();
nonUniqueObjects.forEach(e => uniqueObjects.add(JSON.stringify(e)));
uniqueObjects = Array.from(uniqueObjects).map(e => JSON.parse(e));

console.log(JSON.stringify(uniqueObjects));

var uniqueObjects = new Set();
nonUniqueObjects.forEach(e => uniqueObjects.add(JSON.stringify(e)));
uniqueObjects = Array.from(uniqueObjects).map(e => JSON.parse(e));

5 Comments

I should have mentioned, but I'm trying to do this without using var or let
that is only to show an example. See the updated answer with code.
If uniqueObjects is a const, then you can't assign the Array.from-part to it. You would just end up with 'Uncaught TypeError: Assignment to constant variable.'
you dont need it as a const.
Sorry, but the fact just is that I can only use Const and I know it's doable

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.