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' },
] 
3
  • Does this answer your question? Using spread syntax and new Set() with typescript Commented Oct 28, 2022 at 9:51
  • see 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 stackoverflow.com/a/56768137/13762301). Commented Oct 28, 2022 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) Commented Oct 28, 2022 at 10:18

2 Answers 2

5

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.

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

Comments

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.

Comments

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.