Angular Ordering Map Object

Having an issue that I need help with: I have generated a key-value list and I am looking to sort it in descending order. As you can see in the stackblitz example, I have demonstrated how I create the list and attempt to sort it using different methods. However, the outcome remains the same (sorting them in decreasing order).

Note: I specifically require a key-value list instead of an array.

Stack: https://stackblitz.com/edit/angular-a1yfkd

Answer №1

I have a list with key-value pairs that I want to sort in descending order.

Here's one way to achieve that:

  1. Convert the keys of your map into a string array,
  2. Sort the keys (you can use a custom sorting function if needed),
  3. Create a new object by iterating through the sorted keys and populate it, then return it.

Does this method work for you?

const unsortedList: any = {
  z: 'last',
  b: '2nd',
  a: '1st',
  c: '3rd'
};

function sort(unsortedList: any): any {
  const keys: string[] = Object.keys(unsortedList);
  const sortedKeys = keys.sort().reverse(); //reverse if necessary
  const sortedList: any = {};
  sortedKeys.forEach(x => {
    sortedList[x] = unsortedList[x];
  });
  return sortedList;
}

function sortWithoutUselessVariables(unsortedList: any): any {
    const sortedList: any = {};
    Object.keys(unsortedList)
      .sort() // or pass a custom compareFn there, faster than using .reverse()
      .reverse()
      .forEach(x => sortedList[x] = unsortedList[x])
    return sortedList;
}

console.log('unsorted:', unsortedList);
console.log('sorted:', sort(unsortedList));

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

`Need help setting the active class for a bootstrap navbar using Angular JS?`

In my bootstrap navbar, I have the following menu items: Home | About | Contact I'm looking to assign the active class to each menu item based on the current angular route. Specifically, how can I set class="active" when the angular route is at # ...

Angular noticed a shift in the expression once it was verified

Whenever I try to invoke a service within the (change) action method, I encounter this issue: ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ng-untouched: true'. Cur ...

a guide to effortlessly updating data in ng2-charts in real-time using Firebase

I am brand new to using angular2. My current challenge involves creating a bar chart with the ng2-charts library and connecting it to firebase through angularfire2. I have developed 2 components and a service that is responsible for sending and receiving d ...

Tips for securely encrypting passwords before adding them to a database:

While working with Nest.Js and TypeORM, I encountered an issue where I wanted to hash my password before saving it to the database. I initially attempted to use the @BeforeInsert() event decorator but ran into a roadblock. After some investigation, I disc ...

Slicknav is failing to appear on the screen, although it is being

After spending hours trying to implement a slicknav menu into my school project, I'm stuck and seeking guidance. Despite having some coding experience, I can't seem to find the solution to my problem. Any help, insight, or tips on fixing or impro ...

Is using canvas the best option for creating simple image animations with JavaScript?

I am currently working on a basic animation project using JavaScript. This animation involves switching between 13 different images per second to create movement. I have created two simple methods for implementing this animation. The first method involves ...

I am curious about the significance behind 'this.object.position' within the trackball feature of Three.JS

After spending quite some time delving into the code of this Trackball control, I am puzzled by what exactly this.object.position represents. You can find the code here: https://github.com/mrdoob/three.js/blob/master/examples/js/controls/TrackballControls. ...

What is the best way to retrieve that input value?

Whenever I click "Book Now!" button, I face a major issue in capturing the values of these inputs and linking them to the object named "book". However, no matter where I define the object in my JavaScript code, it simply does not function properly. The obj ...

Differences between a readonly variable and a method with a readonly type in TypeScript

Exploring the Contrast Between Readonly Variables and Readonly-Typed Methods in TypeScript Readonly Variable: maxLength: Readonly<Number | number | String | string> = 1; vs Readonly-Typed Method: maxLength(length: Number | number | String | stri ...

What is the best way to retrieve a specific value from a nested array that is within an array of objects

My goal is to extract a specific field value from a nested array within an object array. Using the map method, I attempted to achieve this but ended up with two empty arrays nested inside two empty objects. Though I am aware of this mistake, it indicates t ...

Ensure that the floated element stretches to 100% height in order to completely fill the page

I'm working on achieving a height of 100% for the left sidebar so that it fills the page regardless of the size of the "main" div. Currently, it stops at the normal page height and doesn't expand further. Is there any way to make this work as i ...

Using the typescript infer feature does not function properly when dealing with arrays

My TypeScript code is causing some unexpected results: const myObject = { foo: ['a', 'b', 'c'] } type MyType = typeof myObject.foo extends [...infer Content] ? string : boolean The type MyType is coming out as 'string ...

Error encountered while trying to retrieve JSON data

After running the following code, I encountered an issue I received an error message stating: Uncaught TypeError: Cannot read property 'searchname' of undefined What could be causing this error and how can I fix it? var selectedVal = "calend ...

What could be causing the audio file not to be received from the front end React to the Python server?

Here is the React code snippet: import React ,{ ChangeEvent, useState } from "react" const FileUpload: React.FC = () => { const [selectedFile, setFile] = useState<File| null>(null); const HandleAudioChange = (event:ChangeE ...

Differentiate the selected level on the DOM

Can someone help me with the following selector? $('#navigation ul li a').click(function(evt) {} It gets the elements I need, but also retrieves child elements. For example, it also selects: #navigation ul li li a // extra li I am curious a ...

Transferring data as a JSON object from PHP to JavaScript

My PHP file is named page.php <?php $php_variable = $_GET['param1']; $uv = str_replace("{ZIP Code}", $php_variable,'http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/{ZIP Code}/JSON'); $homepage = file_get_contents($u ...

Start the CSS3 animation in reverse right away

I am trying to achieve a "flashing" effect by adding the .shown class to my #overlay, causing the opacity to fade in for 2 seconds and then immediately reverse, fading out for another 2 seconds. After experimenting with removing the class, I found that it ...

How can I extract and display chosen values from multiple dropdown menus in designated text boxes based on their unique identifiers?

A website for evaluating car values is in the works, using a combination of PHP, MYSQL, JQUERY, and JavaScript. The database includes 3 tables: Table "car_make": id make 1 BMW Table "model": model_id model_name make_id 1 M3 1 Table "ca ...

Adding elements to a page while it is running can be achieved using a variety

Working on a college project, I am developing a demo web-app in Angular. The goal is to implement a feature where clicking a button adds a new node to the DOM tree. In JavaScript, a simple solution would be: document.getElementById('ticket-container& ...

Using Node.js with the Instagram API resulted in the error message: "Failed to decode a text frame in UTF-8 format."

For my project, I am utilizing the Instagram API with the http node.js module. The API call is quite simple: getJSON : function(options, on_result, on_error) { var req = http.request(options, function(res) { var output = ''; ...