angryip angryip - 1 month ago 16
TypeScript Question

Hashset in Typescript

I am attempting to do something very basic in typescript. Get a list of unique strings while parsing a map as referenced in this post.

Here is what I am attempting to do:

let myData = new Array<string>();
for (let myObj of this.getAllData()) {
let name = myObj.name;
console.log("## we have " + name);
console.log("### is property ? " + myData.hasOwnProperty(name));
if (!myData.hasOwnProperty(name)){
myData.push(name);
}
}


My printout will always evaluate to false for any string, duplicate or not. Here is some sample output:

## we have COW
### is property ? false
## we have COW
### is property ? false
## we have RAODN
### is property ? false
## we have COOL
### is property ? false


However, when the process completes, my list contain duplicates. I have tried looking at this documentation, but there is no mention of a 'hashset' or any set in general.

Is there something equivalent in typescript of a Set? i.e A list of unique elements

Answer

An object {} is a key value pair dictionary is a hash set in JavaScript which TypeScript is a superset of and therefore you can use a JS object to serve in this role.

A quick version from the code you posted:

let myData = {};
for (let myObj of this.getAllData()) {
    let name = myObj.name;
    if (!myData[name]){
        myData[name] = name;
    }
}