Guide to arranging an object in ascending order based on a key's value using JavaScript

Is there a way to sort the following values: 1, 99, 1, 50 in javascript?

Given the input:

var map = {test:1, test2:99, test3:1, test4: 50}

The desired output is:

{test2:99, test4:50, test3:1, test:1}

This is the approach I have attempted:

function sortMap(map) {
    var temp = [];
    for(let prop in map) {
        if(map.hasOwnProperty(prop)) {
            temp.push({name:prop, size:map[prop]});
        }
    }
    return temp.sort(function(b, a) {
        return a.size - b.size
    });
}

Answer №1

To organize an object's keys, it is not possible to directly sort them, but you can sort the keys and access the corresponding values.

var dictionary = { apple: 3, banana: 7, orange: 5, pear: 2 },
    sortedKeys = Object.keys(dictionary).sort(function (a, b) { return dictionary[b] - dictionary[a]; });

sortedKeys.forEach(function (key) {
    document.write(key + ': ' + dictionary[key] + '<br>');
});

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

Tips for structuring commands in Discord.js

I'm in the process of restructuring my bot's commands. I currently have a folder called commands with all my commands inside, but I want to make it more organized by categorizing them into moderators, fun, and global like this: commands > mo ...

Unintended redirects are occurring with AJAX requests when using the send() method

After loading the web page, I utilize AJAX to populate a list asynchronously. However, when the AJAX request is sent to retrieve data for the list box, instead of receiving JSON data as expected, an unintended web page containing the list box is returned. ...

Why does the outcome of running this code vary each time?

I've been working on a code project to create 10 bouncing balls of different colors, but I'm encountering an issue where only one or two balls appear with different colors or the animation works perfectly only 1 out of 10 times. Any thoughts on w ...

Remove a row from an ng-bootstrap table

I've managed to successfully implement the ng-bootstrap table full example. Deleting objects from the DOM and database works fine, but I'm struggling to figure out how to delete a row from the view without having to reload the page. It's i ...

How can you use ng-click to re-sort data that has already been loaded using Angular's ng-click?

I'm having trouble switching between loading and sorting the information in the table using ng-click. The functions to load and sort work correctly individually, but I can't seem to switch between the two. It seems like I reset the countries data ...

Within Codesandbox using Vue, the error message 'The property or method "children" is not defined in the instance, but is referenced during rendering.' appeared

Currently, I am in the process of creating a versatile State Manager that can seamlessly integrate with various Frontend Frameworks, including Vue. In order to showcase how the State Manager can be utilized within Vue, I have set up a simple codesandbox de ...

Is there a way to determine if a JavaScript alert box is currently open in a browser using Ruby and Selenium? If so, what steps can be taken to close

During the process of transitioning between pages with Selenium functions, there are instances where a confirm box appears with options to click OK or cancel. What is the proper way to detect this box and dismiss it? Appreciate the help ahead of time! ...

The refusal to run JavaScript stemmed from an empty MIME type, resulting from the combination of nodeJS, express, engintron, and nginx

Currently, I'm struggling with a frustrating issue that's making me want to pull my hair out. So, here's some important information you need to be aware of: My application is built using node.js (version 16.13.1) with express and nginx man ...

Using three.js to cast rays on a mesh with skinning simulation

Attempting to perform a raycast on a skinned mesh post-skeleton alterations, with no animations involved to prioritize performance. The challenge in this endeavor includes: Load skinned mesh and add it to the scene Make changes to the positions of speci ...

Can you explain the distinction between bodyparser.urlencoded and bodyparser.json?

I'm a bit confused about the use of bodyparser. Why is it necessary when we can simply use json.stringify (to convert an object to a string) and json.parse (to convert JSON to an object)? Is it because by using app.use() with bodyparser, the middlewa ...

In what way can I decipher a section of the URL query string within my AngularJS application?

Here is a snippet of code that I am working with: var search = $location.search(); if (angular.isDefined(search.load) && search.load != null) { if (search.load = "confirmEmail") authService.confirmEmailUserId = search.userI ...

Developing uniform resource locators with jQuery

As I work on developing my webapp, I have made use of the tag in my JSPs to ensure that all links within the application - whether they lead to pages or resources like images and CSS - always stem from the root directory rather than being relative to the ...

Oops! There was a validation error as the duration was not formatted as a number. Please make sure to provide a valid numerical value for the duration field

When attempting to update data from a MongoDB database and checking the results on Postman, an error is encountered. The error reads as follows: "Error: ValidationError: duration: Cast to Number failed for value \"NaN\" at path \"duration&bs ...

Implementing AJAX to dynamically update information based on user's selection from a dropdown

I need to dynamically adjust the opacity of my graph bars without requiring the user to manually refresh the page. I'm considering using AJAX for this purpose. How can I implement this functionality? const opacitySlider = document.getEle ...

Tips on comparing a string against an object's value

I need to compare the key values of an object with the strings yes or no. I am encountering difficulties in achieving this comparison and updating radio buttons accordingly based on the comparison. Here is the code snippet: const screenJson = { Managem ...

There are two distinct varieties of object arrays

I recently encountered an issue while trying to sort my array of Star Wars episodes by episode ID. The problem emerged when comparing two arrays: one manually inputted in the code snippet labeled as "1" on the screenshot, and the other generated dynamicall ...

Karma-coverage examines the test coverage of JavaScript files rather than TypeScript files within Angular 2

I am facing an issue with checking test coverage in TypeScript files using Istanbul and setting test thresholds via karma-coverage. The problem arises because karma-coverage checks test coverage in JavaScript files instead of TypeScript, which leads to mis ...

Exploring Vue and Nuxt JS: What Causes the Issue of Unable to Create the Property 'display' on the String 'bottom:30px;right:30px;'

this piece of code is designed for a component that allows users to jump back to the top of the page. However, after refreshing the page, it stops working and throws an error. The project uses the Nuxt and Vue framework. Can anyone identify the reason behi ...

JavaScript code that moves the active link to the top of the navigation when the window width is less than or equal to 800px

I'm working on a responsive navigation that is fixed at the top and switches from horizontal to vertical when the screen size is less than or equal to 800 pixels wide. However, I'm facing an issue with moving the active link to the top of the na ...

Utilize the Bootstrap column push-pull feature on the mobile version of

https://i.stack.imgur.com/yTBIt.png When viewing the desktop version, div A is displayed at the top of the page. However, I would like to move it to the bottom when viewing on a mobile device (col-xs). I have attempted to solve this issue myself without s ...