0

Similar question but with javascript here. Accepted answer

const data = [
  { group: 'A', name: 'SD' }, 
  { group: 'B', name: 'FI' }, 
  { group: 'A', name: 'MM' },
  { group: 'B', name: 'CO'}
];
const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B']

However if you try the same thing with typescript you get an error ts2802 Type 'Set' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher

How can you achieve the same results with typescript?

Question two How about you want to get unique objects rather than strings . For eample if you want to get

[
  { group: 'A', name: 'SD' }, 
  { group: 'B', name: 'FI' },
] 
Amos Machora
  • 143
  • 6
  • Does this answer your question? [Using spread syntax and new Set() with typescript](https://stackoverflow.com/questions/33464504/using-spread-syntax-and-new-set-with-typescript) – pilchard Oct 28 '22 at 09:51
  • see [How to remove all duplicates from an array of objects?](https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects) if you're looking to remove duplicate objects, not just values. (you'll need to read through all the top-voted answers to find the answer that works best for your use case, but I would look at https://stackoverflow.com/a/56768137/13762301). – pilchard Oct 28 '22 at 10:14
  • Also, don't add a second question to an already answered question. (you do realize that TypeScript is just a superset of javascript? The above linked answer needs just superficial typing to be valid in TypeScript) – pilchard Oct 28 '22 at 10:18

2 Answers2

2

This should solve your issue:

const array = Array.from(new Set(data.map(item => item.group)));

Note: Spreading a Set has issues when compiled with TypeScript. It's safer to use Array.from above instead.

Ali Zgheib
  • 128
  • 2
  • 11
0

Just use compilation target in your tsconfig.json as ES6 or higher:

"compilerOptions": {
  "target": "ES6"
}

Your current target must be ancient, hence the error.

Other than that, your original code is perfectly correct.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138