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
TypeScript set is a new data structure added in ES6 version of JavaScript. It allows us to store distinct data (each value occur only once) into the List similar to other programming languages. Sets are a bit similar to maps, but it stores only keys, not the key-value pairs.
The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.
type emptySet = void; let es: emptySet = null; There is also the never type, which doesn't accept anything, even null .
Sets are a bit like maps but they only store keys not key-value pairs. They are common in other programming languages but are a new addition to JavaScript in ES 6.
It exists!
mySet: Set<string> = new Set<string>();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With