You also can do
Array.from(my_set.values());
Answer from mayan anger on Stack OverflowHow to use array set as const as any other array with same structure?
JavaScript Array to Set - Stack Overflow
need advice on typescript Set<> inefficiency
Benchmark driven development in JavaScript (Set vs. Array)
There are a few arrays set as const:
const MyColors = [
{name: 'Red', hex: '#FF0000'},
{name: 'Green', hex: '#008000'},
{name: 'Purple', hex: '#800080'}
] as const;
const BannedColors = [
{name: 'Orange', hex: '#FFA500'},
{name: 'Blue', hex: '#0000FF'},
{name: 'Purple', hex: '#800080'}
] as const;And there's also a function that converts such arrays to something else:
type ColorsArrayType = { name: string, hex: string }[];
function doSomething(obj: ColorsArrayType) { };
The problem is TypeScript doesn't allow me to pass MyColors or BannedColors to the function because types of their elements are not the same as ColorsArrayType . Since the arrays are set as const, their element types are more precise than just { name: string, hex: string }.
I think using satisfies could solve the problem but I have to use an old version of TypeScript that doesn't support satisfies. And I can't set ColorsArrayType to BannedColors or MyColors because I want to get a union type of all possible color names, that's why I need as const.
Using something like type ColorsArrayType = typeof MyColors | typeof BannedColors is also not an option because there could be more arrays with colors.
What could be a better solution for this?
Just pass the array to the Set constructor. The Set constructor accepts an iterable parameter. The Array object implements the iterable protocol, so its a valid parameter.
var arr = [55, 44, 65];
var set = new Set(arr);
console.log(set.size === arr.length);
console.log(set.has(65));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
See here
If you start out with:
let array = [
{name: "malcom", dogType: "four-legged"},
{name: "peabody", dogType: "three-legged"},
{name: "pablo", dogType: "two-legged"}
];
And you want a set of, say, names, you would do:
let namesSet = new Set(array.map(item => item.name));