TypeScript's HashSet Implementation

I'm working on a simple TypeScript task where I need to extract unique strings from a map, as discussed in this post.

Here's the code snippet I'm using:

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.includes(name));
    if (!myData.includes(name)){
        myData.push(name);
    }
}

Even though the console output shows that each string being processed isn't already in the array, I still end up with duplicates at the end. Here's an example of the 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

I've checked the TypeScript documentation, but couldn't find any reference to a 'hashset' or set for unique elements.

Is there an equivalent in TypeScript to a Set for maintaining a list of unique elements?

Answer №2

In JavaScript, an object is essentially a key-value pair dictionary or a hash set. TypeScript, being a superset of JavaScript, allows you to use a JS object in this capacity.

Here's a simplified version based on the code snippet you provided:

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

Answer №3

After some experimentation, I managed to come up with my own approach:

const uniqueNames = Array.from(new Set(this.getAllData().map(obj => obj.name)));

I'm not entirely sure if this is the optimal solution compared to others suggested thus far, but for now, it's the method I've settled on until a more efficient alternative becomes apparent.

Answer №4

While doing some research, I stumbled upon a potentially useful resource - check out this link:

This site includes type definitions specifically tailored for Type Script.

If you're interested in exploring further, here's another link that might be of interest: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/0b5bfba2994c91a099cd5bcfd984f6c4c39228e5/types/hashset/index.d.ts

This resource offers implementation of a genuine HashSet, complete with functions like equals and hashcode, as well as buckets and more.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for the ngFor loop in Ionic 5 component not functioning properly?

I'm facing an issue with the *ngFor directive in one of my components. It's strange because it works fine in other components. Can anyone help me figure out what I might be doing wrong? @Component({ selector: 'app-age-picker', temp ...

Using Firebase with the async pipe in Angular 5

I am struggling to implement async pipe in Angular firebase and encountering an error that I cannot resolve: ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' Utilizing the Firebase NoSQL database: { "bos ...

Challenges encountered when using promises for handling mysql query results

I've been working on creating a function that will return the value of a mysql query using promises. Here's what I have so far: query(query: string): string { var response = "No response..."; var sendRequest = (query:string): Prom ...

Tips for displaying an array and iterating through its children in Angular 7

I am currently working on extracting the parent and its children to an array in order to display them using ngFor. However, I am encountering an issue where the children are not being displayed during the ngFor. I have a service that retrieves data from a ...

What is the process for defining a default value for a template-driven form input in Angular 2?

I have a simple input element in my form that requires a default initial value to be set. <input type="number" name="interest_rate" [(ngModel)]="interest_rate"> In my code, I included this.form.controls['interest_rate'].patchValue(this.a ...

What is the most effective method for creating Typescript type predicates that yield the most specific types when filtering arrays?

I believed I had discovered the perfect method for defining predicates: declare function isNumber<T>(x: T): x is Extract<T, number>; declare function isFunction<T>(x: T): x is Extract<T, Function>; ... and so forth This technique l ...

Generate gzipped files using Angular CLI

I am attempting to populate a dist folder with the standard files along with their .gz versions. To achieve this, I used ng eject to obtain the webpack.config.js file in order to integrate the compression plugin from https://github.com/webpack-contrib/comp ...

Determining the return type based on the parameter type

Here is an example of my function: const safeIdCastToNumber = (id: string | null | undefined) => isNil(id) ? id : Number(id) When calling safeIdCastToNumber, I can use an id parameter with a type union string | null | undefined, as well as one with a t ...

The clash between the definitions of identifiers in this file and another (@types/jasmine) is causing error TS6200

While trying to build my project with Angular CLI, I am encountering the following error message: ERROR in ../my-app/node_modules/@types/jasmine/index.d.ts(18,1): error TS6200: Definitions of the following identifiers conflict with those in another file: ...

"Setting up a schema in TypeORM when connecting to an Oracle database: A step-by-step guide

As a newcomer to TypeORM, I'm using Oracle DB with Node.js in the backend. Successfully connecting the database with TypeORM using createConnection(), but struggling to specify the schema during connection creation. One workaround is adding the schem ...

Guide to incorporating code coverage in React/NextJs using Typescript (create-next-app) and cypress

I initiated a fresh project using create-next-app with the default settings. npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="365544535742531b58534e421b57464676070518021801">[email protected]</a> --- Would you l ...

What is the best way to assign JSON values to my class property?

I've been working on a weather application that showcases the current weather of 5 different cities. By clicking on each city, users can access a detailed view displaying the 5-day forecast for that particular location. Currently, I have defined a we ...

I encountered an Angular error that is preventing me from updating and uploading images to my Firebase Storage because it is unable to locate the storage bucket

Hey there fellow developers! I'm currently working on a simple Angular app that allows users to upload images to a gallery. However, I've encountered an issue while trying to upload the images to Firebase Storage. I keep getting an error mentioni ...

Toggle the enableCheckboxSelector based on a specific condition

In my implementation of angular slickgrid, the enableCheckboxSelector is set to true by default in the grid options. However, I need to selectively hide checkboxes for all rows based on a dropdown value change. I tried the following code snippet: if(isRead ...

Comparing JSON import methods: HTTP vs require

I discovered two methods for importing local json files into my code. Using angulars http get. This method is well-known for loading json input. It provides the flexibility to easily switch between remote and local json files. Typescript require Anot ...

Breaking up and Substituting text within Angular 8's HTML structure

When I retrieve data from a REST api, I need to split the name parameter at '2330' and insert a line break. For example, if the name is: ABCD 2330 This is My Name, I want the output on my screen to appear as: ABCD 2330 This is My Name // this par ...

What is the best way to retrieve the parameter of ng2-file-upload using endback?

I am attempting to retrieve a parameter using PHP in order to save it into a folder. However, my code is not working as expected. Here is the code snippet: Using the Ionic framework this.uploader.onBeforeUploadItem = (item: any) => { this.uploader ...

Creating custom designs for a HTML button using CSS

Within an HTML form, there are two buttons set up as follows: <button kmdPrimaryButton size="mini" (click)="clickSection('table')">Table View</button> <button kmdPrimaryButton size="mini" (click)=&quo ...

Preventing over-purchasing products by managing Knex.js inventory levels

Currently, I am in the process of developing an online store for my school's guild organization. I must admit that I lack experience working with databases and Knex.js is still a bit challenging for me. An issue arises when multiple users simultaneo ...

Learning to retrieve the value from a dynamically generated input tag in a TypeScript file

<div *ngFor="let task of arrayList"> <input id="task.fieldName" *ngIf="task.key === 'Others'" type="text" class="form-control"> </div> When dealing with dynamically created input fields based on a condition, the challenge is ac ...