Skip to content
Fix Code Error

Sorting object property by values

March 13, 2021 by Code Error
Posted By: Anonymous

If I have a JavaScript object such as:

var list = {
  "you": 100, 
  "me": 75, 
  "foo": 116, 
  "bar": 15
};

Is there a way to sort the properties based on value? So that I end up with

list = {
  "bar": 15, 
  "me": 75, 
  "you": 100, 
  "foo": 116
};

Solution

Move them to an array, sort that array, and then use that array for your purposes. Here’s a solution:

var maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 8 * 60 * 60
};
var sortable = [];
for (var vehicle in maxSpeed) {
    sortable.push([vehicle, maxSpeed[vehicle]]);
}

sortable.sort(function(a, b) {
    return a[1] - b[1];
});

//[["bike", 60], ["motorbike", 200], ["car", 300],
//["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do. That would work in all the browsers I know of, but it would be dependent on an implementation quirk, and could break at any time. You should never make assumptions about the order of elements in a JavaScript object.

var objSorted = {}
sortable.forEach(function(item){
    objSorted[item[0]]=item[1]
})

In ES8, you can use Object.entries() to convert the object into an array:

const maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 8 * 60 * 60
};

const sortable = Object.entries(maxSpeed)
    .sort(([,a],[,b]) => a-b)
    .reduce((r, [k, v]) => ({ ...r, [k]: v }), {});

console.log(sortable);

In ES10, you can use Object.fromEntries() to convert array to object. Then the code can be simplified to this:

const maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 8 * 60 * 60
};

const sortable = Object.fromEntries(
    Object.entries(maxSpeed).sort(([,a],[,b]) => a-b)
);

console.log(sortable);
Answered By: Anonymous

Related Articles

  • How do I include certain conditions in SQL Count
  • Add multiple items to a list
  • Backbone.js Uncaught TypeError this.model.each is…
  • Sort table rows In Bootstrap
  • Group by with union mysql select query
  • Vue - Deep watch change of array of objects, either…
  • Extending React.js components
  • Inferring properties from extended interface
  • Issues with updating an inventory in Python Code
  • How to convert image into byte array and byte array…
  • Getting infinite loop after entering 2 objects to…
  • Beginner Python: AttributeError: 'list' object has…
  • Fix top buttons on scroll of list below
  • Unexpected end of JSON input while parsing
  • How to add X-Total-Count to header response in…
  • how create a simple object animation in processing
  • Form field border-radius is not working only on the…
  • How to use html template with vue.js
  • sorting an array by using pointer arithmetic
  • Remove corresponding item when delete button is…
  • java.lang.IllegalStateException in iterator.remove()
  • How do I remove single children in a tree?
  • Using templates as select option name in Aurelia
  • Problems with automating the function jquery
  • Javascript sort array of objects based on another array
  • Ruby class instance variable vs. class variable
  • Passing objects inside query string in MVC 4 and Backbone.js
  • Search specific data in vue b-table from axios API
  • Polymer static variable listener?
  • Sorting Backbone Collections
  • How to Deserialize XML document
  • Vue.js - emit to update array not working
  • How to get a value inside an ArrayList java
  • Room @Relation with two foreign keys
  • Is it possible to apply CSS to half of a character?
  • What's the correct way to pass props as initial data…
  • Check if value exists in enum in TypeScript
  • Call useQuery after retrieving router query object…
  • don't know what went wrong nav bar with Tailwind CSS…
  • How can I throw a general exception in Java?
  • Static Vs. Dynamic Binding in Java
  • What is the origin of foo and bar?
  • What does this symbol mean in JavaScript?
  • Angular 2 - Setting selected value on dropdown list
  • Javascript dynamic sorting array of object include…
  • summing two columns in a pandas dataframe
  • How delete an item using vuex?
  • Sortable.js with Vue 2.0 sorts incorrectly
  • Dependent/Cascading Dropdowns in Aurelia
  • Insert javascript code for responsive iframe in Vue.js
  • JavaScript override methods
  • Usage of __slots__?
  • How to sort an array in descending order in Ruby
  • Having issue while updating the records in laravel…
  • Vuetify 2.2 DataTable multiple filters
  • Increasing size of semi circle using css
  • Ember.js: rendering google chart in template (AKA…
  • Make drag & drop sort order in Vue.js start at 1, not 0
  • How to sort a array of object based on a key and set…
  • Active tab issue on page load HTML
  • How to access sub element's attached behavior?
  • What are forward declarations in C++?
  • SVG Mask is "bleeding" on canvas edges
  • An Authentication object was not found in the…
  • Programmatically Lighten or Darken a hex color (or…
  • Possible to use a let within an if/cond?
  • sortable issue in element-ui
  • Adding CSS to jQuery dynamically added element…
  • How to find length of a string array?
  • What's the difference between utf8_general_ci and…
  • How to keep image proportions the same when using grid?
  • How to easily initialize a list of Tuples?
  • Vuetify grid column wrap fill full height
  • How to parse deserialized object back into arrays?
  • C threads corrupting each other
  • create a new column with pandas groupby division…
  • Javascript text animation not triggering
  • After a little scroll, the sticky navbar just is not…
  • Generate sequence of dates for given frequency as…
  • Difference between variable declaration syntaxes in…
  • How can I access and process nested objects, arrays or JSON?
  • SortableJS / Vue.Draggable multi-drag option not working
  • How can I run this simple for loop in parallel bash?
  • Is this request generated by EF Core buggy or is it my code?
  • How to bind a sortable list to vuejs?
  • How to insert string values into a empty created…
  • Semaphore vs. Monitors - what's the difference?
  • Trouble with boxes appearing/hiding based on selection
  • Replace the UUIDs with Strings
  • Continuously adding to a dictionary
  • Use of Jquery on scroll event
  • How does the Backbone.js url function work?
  • What does "Fatal error: Unexpectedly found nil while…
  • Handling null value in Web API
  • dplyr lag function multiple nested data
  • Sort a list of numerical strings in ascending order
  • Why iot_thread stack overflow is coming when I m…
  • How to find the sum of a specific key in array of objects
  • What is your most productive shortcut with Vim?
  • Multiple rows to one comma-separated value in Sql Server

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to print a dictionary’s key?

Next Post:

How to check if any value is NaN in a Pandas DataFrame

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error