Steps to find the most common element in a string array using TypeScript

Below is an object that I am working with:

export namespace Data {
  export type AsObject = {
    a: string,
    b: string,
    c: string,
    d: number,
  }
}

I am looking to identify the most frequent occurrence of the string Data.AsObject.a within Data.AsObject[]. If anyone has a TypeScript code snippet that can accomplish this, I would greatly appreciate it. Thank you!

Answer №1

In the scenario where the array is empty or there is a tie for the greatest occurrence, an error will be triggered as I have implemented conditions to handle these cases:

  • If the array is empty, an error will be thrown
  • If there is a tie, only one value will be returned (the first one that occurs)

If you wish to alter this behavior, adjustments will need to be made accordingly.

This implementation also allows you to find the highest occurrence of any other property: simply change the specified key as the second argument.

https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/HYQwtgpgzgDiDGEAEAREAXESDeBYAUEkhAB4wD2ATukugJ4zICCUA8gEYBWE8NAvDgJEiIAFxIo6SgEtgAcwDcQ4e3GSZ8pYWHw1U2YuVEAJuOABXMOwiUtRAL5b7BAgHpXSAJIAzWgAsbCAByKCQsdGkIABokcmAAGzpY4GRpUMoIdHNKFOMCb3NgXmk4pDkMjGh0Vnh4bIyi5AAeAGliEnQIYGNQgGsIOnJfNEwAOhYObl...ambiguous:true allowjsdoc:false compilerOptionsRtw:true #solutions

namespace Data {
  export type AsObject = {
    a: string;
    b: string;
    c: string;
    d: number;
  };
}

// If there's a tie, only one is returned
function greatestOccurrence <K extends keyof Data.AsObject>(
  arr: Data.AsObject[],
  key: K,
): Data.AsObject[K] {
  type T = Data.AsObject[K];
  const map = new Map<T, number>();

  for (const o of arr) {
    const item = o[key];
    map.set(item, (map.get(item) ?? 0) + 1);
  }

  const result = [...map].sort(([, a], [, b]) => b - a)[0]?.[0];
  if (typeof result === 'undefined') throw new Error('Array is empty');
  return result;
}

///// Use like this:

// Example with incomplete props:
const items = [
  {a: 'hello'},
  {a: 'hello'},
  {a: 'hola'},
  {a: 'willkommen'},
  {a: 'bonjour'},
  {a: 'hola'},
  {a: 'hola'},
] as Data.AsObject[];

const result = greatestOccurrence(items, 'a');
console.log(result); // "hola"

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

Executing an HTTP POST request within an Angular 7 route guard: A step-by-step guide

In my Angular 7 application, I have implemented a route guard that is dependent on the response of a post call. The guard is structured like this: canActivate = (_router: ActivatedRouteSnapshot): boolean => { console.log('in link expiry guard& ...

Having trouble integrating ColorThief with Angular, encountering issues with missing library methods?

I am attempting to integrate the Library ColorThief () into an Angular 12 project, but unfortunately, I have been unable to make it work. I started by running $ npm i --save colorthief and then in my desired component .ts file: const ColorThief = require ...

Is there a way to expand the return type of a parent class's methods using an object

Currently, I am enhancing a class by adding a serialize method. My goal is for this new method to perform the same functionality as its parent class but with some additional keys added. export declare class Parent { serialize(): { x: number; ...

Issue with Typescript when attempting to create an array of objects with varying keys using the map method

My goal is to dynamically create an array of objects, each potentially containing different keys but always following the same format as defined on myType. However, Typescript throws an error when I attempt to do so. Below is a simplified example. type myT ...

Incorporate matter-js into your TypeScript project

Upon discovering this file: https://www.npmjs.com/package/@types/matter-js I ran the following line of code: npm install --save @types/matter-js When I tried to use it in the main ts file, an error message appeared: 'Matter' refers to a U ...

Utilizing a JSDoc comment from an external interface attribute

Currently, I am in the process of developing a React application. It is common to want the props of a child component to be directly connected to the state of a parent component. To achieve this, I have detailed the following instructions in the interface ...

How can I limit the input of string values from a Node Express request query?

export type TodoRequest = { order?: 'asc' | 'desc' | undefined; } export const parseTodoRequest = (requestData: ParsedQs): TodoRequest => { return { order: requestData.order as 'asc' | 'desc' | u ...

AngularJS 2: Modifications to templates or components do not automatically reflect in the user interface

My background is in Angular 1, where everything worked seamlessly. However, I am encountering serious issues trying to create a basic application using Angular 2 in Visual Studio. After carefully following the "5 minute tutorial" and getting it to work, I ...

Proper method for handling incoming requests using Typescript and Express

When it comes to validating incoming requests using zod and generating types with the infer functionality, I find myself wondering about the best way to specify these types in my Express controller. Imagine I have an endpoint that requires a body structur ...

Generate a new component within another dynamically generated component

In my endeavor to dynamically create a component within another dynamically created component, I am facing a unique challenge. Below is the code snippet: export class DefaultLayoutComponent { constructor(private cdRef: ChangeDetectorRef, public defa ...

Are Typescript generics that use "extends object" unnecessary? How should this be approached for best practices?

In my observations, using the <P extends object> generic in JavaScript is often deemed pointless since virtually everything in the language is an object. Most literals behave like objects with methods such as .toString, and strings are objects with p ...

Gain insights on Stripe Webhooks with Firebase Functions and Node.js

I've been struggling to integrate Firebase functions with Stripe webhooks for listening to events. Take a look at my code: exports.stripeEvents = functions.https.onRequest((request, response) => { try { const stripeSignature = request. ...

Encountering a non-constructor error while trying to import packages in React Typescript

I am currently working on a project that utilizes React with Typescript. While attempting to import a package, I encountered an error stating that the package lacks a constructor when I run the file. This issue seems to be prevalent in various packages, a ...

This TypeScript error indicates that the variable may be undefined (Error code: 18048)

One of the challenges I encountered in my Angular project was with an interface defined in userinterface.ts export interface Done { wordlen: number; word: string; }; I utilized this interface to populate an array like so donearr: Done[] = []; ...

How to retrieve the declaring type from a static method in TypeScript

Looking for a way to determine the type that declares a static method. This needs to be functional even with subclasses. class Animal { static getType(): any { // Want to return the declaring type of this method, // For example, Animal ...

Top tips for defining or assigning data types

As a newcomer to TypeScript on my first day, I have experience working on JavaScript projects above the average level. I am seeking advice on best practices and standards for declaring or assigning types in code. Currently, I tend to specify types for ever ...

Converting a unix timestamp to a Date in TypeScript - a comprehensive guide

To retrieve the unix timestamp of a Date in plain JavaScript and TypeScript, we can use this code snippet: let currentDate = new Date(); const unixTime = currentDate.valueOf(); Converting the unix timestamp back to a Date object in JavaScript is straight ...

Unable to handle errors when making API requests

I'm currently working on a custom hook and I need to handle errors that may occur during an API call to adjust the display. Here's the code for the custom hook: function useBook() { const [book, setBook] = useState<Book | any>() con ...

What would be a colloquial method to retrieve the ultimate result from the iterator function?

I've got a rather complex function that describes an iterative process. It goes something like this (I have lots of code not relevant to the question): function* functionName( config: Config, poolSize: number ): Generator<[State, Step], boo ...

Angular does not display HTML content until the requested http data has been fully loaded

I am experiencing an issue where certain HTML content does not load until the component has received data from an API call through a service. Below is the relevant code snippet: import { ApiService } from './services/api.service'; @Component({ ...