Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert each Array in a typescript object to a set

I am a beginner in Typescript, and I am looking for a neat way to convert all the arrays in an object to a set.

Input:

const inputObject = {'a': [1, 2, 3], 'b': [2, 2, 2], 'c': [3,3,2,4]};

Output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'a': Set(3){1, 2, 3}, 'b': Set(1){2}, 'c': Set(3){2, 3, 4};

I know how to work on it iteratively key by key and get the solution. I am looking if I can do it more elegantly and modify the same inputObject instead of creating a new object.

>Solution :

This code works, but not sure why it isn’t working in StackOverflow’s code editor.

You need to do the following

  1. get the keys of the object you are trying to modify
  2. Update each of them as Set.
const inputObject = {'a': [1, 2, 3], 'b': [2, 2, 2], 'c': [3,3,2,4]};
console.log(inputObject);
Object.keys(inputObject).forEach(key => inputObject[key] = new Set(inputObject[key]));
console.log(inputObject);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading