Reputation: 19
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.
Upvotes: 0
Views: 916
Reputation: 19
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.
Upvotes: 1
Reputation: 34673
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));
Upvotes: 0
Reputation: 26360
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)
Upvotes: 1