Is it possible to easily organize a TypeScript dictionary in a straightforward manner?

My typescript dictionary is filled with code.

var dictionaryOfScores: {[id: string]: number } = {};

Now that it's populated, I want to sort it based on the value (number).

Since the dictionary could be quite large, I'm looking for an in-place solution.

Although there is a typescript-collections package available, I prefer a simple method without adding extra libraries.

The Sort JavaScript object by key explains a javascript approach to sorting TypeScript objects, but it creates a copy and doesn't specifically mention dictionaries.

Answer №1

My approach to achieving this task was as follows:

const scoreDictionary: {[id: string]: number } = {
  Fred: 11,
  George: 22,
  Toby: 18,
  Shannon: 15,
}

const sortableArray = Object.entries(scoreDictionary);
const sortedArray = sortableArray.sort(([, a], [, b]) => a - b);
const sortedObject = Object.fromEntries(sortedArray);
console.log(sortedObject)

The expected output would be:

{
  Fred:11,
  Shannon:15,
  Toby:18,
  George:22
}

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

TS2307 error encountered in Angular 2 TypeScript due to the inability to locate a module for a private npm

I've been working on creating some components for internal company use, with the intention of sharing them through our private npm repository. However, I've hit a roadblock while trying to add these components to an app using npm and systemjs - I ...

Struggle between Angular and fundamental CSS principles

Upon following the steps below, I aim to achieve my desired grids: How to set auto-margin boxes in flexible-width design using CSS? The solution provided is effective when implemented outside of Angular. However, when inserted inside an Angular component ...

Navigating to the detail page following a POST request in RTK query: A step-by-step guide

In my React RTK-query form, I am facing an issue where after a POST request is made, the form should navigate to the next step. However, in order to do that, I need to obtain the id of the newly created record. The backend auto-increments the id and does n ...

Inversify's Http Context consistently remains void of any content

Hello there, I'm in need of assistance with building an API using inversify and inversify-express-utils. Everything seems to be working fine with my controllers and the API so far, except for one issue. When trying to access the httpContext property i ...

Creating an empty TypeScript variable with type FileList can be achieved by declaring the variable and initializing it with

After completing a coding test that required building a react app for uploading files using Typescript, I encountered a dilemma. Specifically, I needed to use the useState hook to store the uploaded file and set its default value. Typically, setting the de ...

How can you apply an active class using React-Router?

My React-Router navigation issue nav.tsx import React from 'react' import { menu } from './menu' import { Link } from 'react-router-dom' import styles from './HamburgerMenu.module.scss' const HamburgerMenu: React.F ...

How to retrieve the value of an input field in Angular 2/Typescript without using ngModel

Currently, I'm utilizing Typescript in conjunction with Angular2, mirroring the structure of the Angular2 Tour of Heroes guide. There is a specific input field that I aim to associate a change event with, triggering custom logic whenever the value wi ...

What could be causing TypeScript to raise an issue when a /// reference comes after the 'use strict' statement?

This particular inquiry is somewhat connected to a question I posted on Stack Overflow yesterday about why TypeScript is encountering issues when trying to import a module. The initial configuration remains unchanged. My TypeScript file appears as follows ...

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...

What is the process for developing a bespoke TypeScript Declaration library and integrating it into my projects through NPM or GitHub Packages?

Project Description I am currently developing a customized TypeScript type declaration library that will be utilized in various projects. However, I am encountering an issue when it comes to importing this TypeScript library into my projects. Although it ...

What are the steps to retrieve the original source code of an HTML file, specifically in Angular 2 RC4

Is there a way to retrieve the source code that I manually typed in my IDE using JavaScript? Note: I am working with angular2 rc4. I attempted to access it using Reflect.getMetadata, but encountered errors indicating that it is not functioning properly. ...

Choosing and Duplicating Text in Angular

I'm attempting to give the user the ability to select a paragraph and copy it by clicking a button. However, my current code is not working as expected. I initially tried importing directives but encountered errors, prompting me to try a different met ...

Guide to simulating Twilio with Jest and TypeScript to perform unit testing

Please assist me in mocking a Twilio service that sends messages using Jest to mock the service. Below is the code I am working with: import { SQSEvent } from "aws-lambda"; import { GetSecretValueResponse } from "aws-sdk/clients/secretsmanag ...

Unable to perform a default import in Angular 9 version

I made adjustments to tsconfig.json by adding the following properties: "esModuleInterop": true, "allowSyntheticDefaultImports": true, This was done in order to successfully import an npm package using import * as ms from "ms"; Despite these changes, I ...

Sweetalert seems to have hit a roadblock and is not functioning properly. An error has been detected in its TS file

Currently, I am responsible for maintaining an application that utilizes Angular 7.0.7 and Node 10.20.1. Everything was running smoothly until yesterday when my PC unexpectedly restarted. Upon trying to run ng serve, I encountered the following error: E ...

Utilizing TypeScript to Retrieve the Parameter Types of a Method within a Composition Class

Greetings to the TS community! Let's delve into a fascinating problem. Envision having a composition interface structured like this: type IWorker = { serviceTask: IServiceTask, serviceSomethingElse: IServiceColorPicker } type IServiceTask = { ...

What is the reason for not requiring checks with Union Types when utilizing a variable, yet necessitating them within a function?

Currently working on some Typescript challenges and encountered a scenario involving a union type. In this example, the function getIstanbulPostalCode is declared to return either a string or a number: function getIstanbulPostalCode(): string | number { ...

When utilizing ng2-bootstrap, there is no directive that is defined with the "exportAs" attribute set to "bs-modal"

I found a tutorial that I am trying to emulate from this website However, when I insert the template into my HTML file <div class="modal fade" bsModal #staticModal="bs-modal" [config]="{backdrop: 'static'}" tabindex="-1" role="dialog" ...

Assigning a specific data type to an object in TypeScript using a switch case statement

I am currently developing a React Native app using TypeScript. As part of my development, I am creating a handler with a switch case structure like the one below: export const handleMessageData = (dispatch: Dispatch, messageData: FCMMessage): void => ...

What is the best way to create a linear flow when chaining promises?

I am facing an issue with my flow, where I am utilizing promises to handle the process. Here is the scenario: The User clicks a button to retrieve their current position using Ionic geolocation, which returns the latitude and longitude. Next, I aim to dec ...