Sorting objects by property values

javascript sort object by value
javascript sort array of objects by key value
javascript sort object by key
javascript sort array of objects by number
angular 6 sort array of objects by property
javascript sort array of objects by multiple properties
typescript sort array of objects
javascript sort array of objects by string property

How to implement the following scenario using Javascript only:

  • Create a car object with properties (top speed, brand, etc.)
  • Sort a list of cars ordered by those properties

Sorting object property by values, 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:  Well, that means if you are trying to construct the new object after sorting it by property value or anything else, the property key ordering becomes again undefined. Chrome, for example, is by default ordering the property keys, thus every attempt to order them differently is useless.

Example.

This runs on cscript.exe, on windows.

// define the Car class
(function() {
    // makeClass - By John Resig (MIT Licensed)
    // Allows either new User() or User() to be employed for construction.
    function makeClass(){
        return function(args){
            if ( this instanceof arguments.callee ) {
                if ( typeof this.init == "function" )
                    this.init.apply( this, (args && args.callee) ? args : arguments );
            } else
                return new arguments.callee( arguments );
        };
    }

    Car = makeClass();

    Car.prototype.init = function(make, model, price, topSpeed, weight) {
        this.make = make;
        this.model = model;
        this.price = price;
        this.weight = weight;
        this.topSpeed = topSpeed;
    };
})();


// create a list of cars
var autos = [
    new Car("Chevy", "Corvair", 1800, 88, 2900),
    new Car("Buick", "LeSabre", 31000, 138, 3700),
    new Car("Toyota", "Prius", 24000, 103, 3200),
    new Car("Porsche", "911", 92000, 155, 3100),
    new Car("Mercedes", "E500", 67000, 145, 3800),
    new Car("VW", "Passat", 31000, 135, 3700)
];

// a list of sorting functions
var sorters = {
    byWeight : function(a,b) {
        return (a.weight - b.weight);
    },
    bySpeed : function(a,b) {
        return (a.topSpeed - b.topSpeed);
    },
    byPrice : function(a,b) {
        return (a.price - b.price);
    },
    byModelName : function(a,b) {
        return ((a.model < b.model) ? -1 : ((a.model > b.model) ? 1 : 0));
    },
    byMake : function(a,b) {
        return ((a.make < b.make) ? -1 : ((a.make > b.make) ? 1 : 0));
    }
};

function say(s) {WScript.Echo(s);}

function show(title)
{
    say ("sorted by: "+title);
    for (var i=0; i < autos.length; i++) {
        say("  " + autos[i].model);
    }
    say(" ");
}

autos.sort(sorters.byWeight);
show("Weight");

autos.sort(sorters.byModelName);
show("Name");

autos.sort(sorters.byPrice);
show("Price");

You can also make a general sorter.

var byProperty = function(prop) {
    return function(a,b) {
        if (typeof a[prop] == "number") {
            return (a[prop] - b[prop]);
        } else {
            return ((a[prop] < b[prop]) ? -1 : ((a[prop] > b[prop]) ? 1 : 0));
        }
    };
};

autos.sort(byProperty("topSpeed"));
show("Top Speed");

Sorting objects in JavaScript e.c. how to get sorted values from an , An object type is a collection of key-value pairs — properties in JavaScrip. KEY can be a string or a symbol, and VALUE can be any type (str, int  The Sort-Object cmdlet sorts objects in ascending or descending order based on object property values. If sort properties are not included in a command, PowerShell uses default sort properties. You can sort objects by a single property or multiple properties.

I have wrote this simple function for myself:

function sortObj(list, key) {
    function compare(a, b) {
        a = a[key];
        b = b[key];
        var type = (typeof(a) === 'string' ||
                    typeof(b) === 'string') ? 'string' : 'number';
        var result;
        if (type === 'string') result = a.localeCompare(b);
        else result = a - b;
        return result;
    }
    return list.sort(compare);
}

for example you have list of cars:

var cars= [{brand: 'audi', speed: 240}, {brand: 'fiat', speed: 190}];
var carsSortedByBrand = sortObj(cars, 'brand');
var carsSortedBySpeed = sortObj(cars, 'speed');

Sorting an array of objects, The sort() method can be used to sort the array based on the values of one of these properties, such as sorting the array by name, age, or even when they retire. The basic idea is to modify the compare function so it compares the desired properties' values. PowerShell – Sort-Object cmdlet – Sorts objects by property values. Displaying the results in sorted order is an essential feature every tool or language has to provide in order to the users to provide the flexibility to play with the data. PowerShell also provides Sort-Object cmdlet to sorts objects by it’s property values.

Let us say we have to sort a list of objects in ascending order based on a particular property, in this example lets say we have to sort based on the "name" property, then below is the required code :

var list_Objects = [{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}];
Console.log(list_Objects);   //[{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}]
    list_Objects.sort(function(a,b){
        return a["name"].localeCompare(b["name"]); 
    });
Console.log(list_Objects);  //[{"name"="Abhi"},{"name"="Bob"},{"name"="Jay"}]

Quick Tip: How to Sort an Array of Objects in JavaScript, If you have an array of objects that you need to sort into a certain order, operator is also used to check the data type of the property's value. You want to render this list, but first you want to order it by the value of one of the properties. For example you want to order it by the color name, in alphabetical order: black, red, white. You can use the sort() method of Array , which takes a callback function, which takes as parameters 2 objects contained in the array (which we call a and b ):

A version of Cheeso solution with reverse sorting, I also removed the ternary expressions for lack of clarity (but this is personal taste).

function(prop, reverse) {
  return function(a, b) {
    if (typeof a[prop] === 'number') {
      return (a[prop] - b[prop]);
    }

    if (a[prop] < b[prop]) {
      return reverse ? 1 : -1;
    }

    if (a[prop] > b[prop]) {
      return reverse ? -1 : 1;
    }

    return 0;
  };
};

JavaScript: sort object properties by value (numeric or string) · GitHub, by name, age, or even when they retire. The basic idea is to modify the compare function so it compares the desired properties' values. Sorting objects by property values. Ask Question Asked 10 years, 2 months ago. Active 5 months ago. Viewed 94k times 81. 21. How to implement the following scenario

Sort an Array of Objects by Values of Object's Properites in JavaScript, How do you sort an array of objects in JavaScript? I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTo which according to some research is a method for Strings.. I wanted to sort an ArrayList of custom objects by one of their properties: a Date object (getStartDay()).

Array.prototype.sort(), Sort object properties by value (values are text). I have following object: var cities​={10:'Tashkent', 14:'Karakalpakiya', 16:'Andijan'};. I want sort it by city names,  In this article we will look at one way you can sort a list of objects by property values. We will bind a List to a GridView and use GridView sorting to demo this.

How to sort an array of objects by a property value with priority in , Sort an Array of Objects in JavaScript​​ Summary: in this tutorial, you will learn how to sort an array of objects by the values of the object's properties. To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects. The Property parameter of the Sort-Object cmdlet accepts an array (more than one) of properties upon which to sort. This means that I can sort on the process name, and then sort on the working set of memory that is utilized by each process (for example).

Comments
  • @durilai: JavaScript is object oriented, the OO model of JavaScript is based on Prototyping and is really, really versatile... en.wikipedia.org/wiki/Prototype-based_programming
  • I recommend to use lodash.js : lodash.com/docs#sortBy
  • Simple note for convenience: this (a.someProp - b.someProp) sorts from lowest to highest, and the reverse (b.someProp - a.someProp) sorts from highest to lowest. Basically, if the function returns less than 0, a comes before b.
  • Also note that this solution only works for when the properties you're sorting by are numbers. This works in the example for sorting by top speed, but if you want to sort by car brand, this solution won't sort strings alphabetically. Cheeso provides an answer for sorting by both numbers and strings.
  • I think you have a typo? return a["name"].localeCompare(b.["name"]); should be return a["name"].localeCompare(b["name"]); (remove the . after b)
  • To be fully reversed the numbers need return !!reverse ? (a[prop] - b[prop]) * -1 : (a[prop] - b[prop]);
  • Yes, as now no reverse check on numbers, thank you, I should fix that. But why the double ! this is fine too: return reverse ? (a[prop] - b[prop]) * -1 : (a[prop] - b[prop]);
  • The !! forces type coercion to a native boolean type value as opposed to the "falsy" nature of the JavaScript value, not strictly needed but clarifies purpose at least to me. Note that when you return a value with !! it is a native Boolean type as opposed to a native type with a "falsy" value which is to say the typeof !!undefined or typeof !!null etc. return "boolean" Note that !!" " is true but !!"" is false (space, no space in the string) but you probably knew that already.