Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting objects by property values

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
like image 827
Constructor Avatar asked Mar 17 '10 22:03

Constructor


People also ask

How do you sort an object by property in powershell?

If you want to sort by multiple properties, separate the properties by commas. The Get-ChildItem cmdlet gets the files from the directory specified by the Path parameter. The objects are sent down the pipeline to the Sort-Object cmdlet.

How do you sort an array of objects based on the key?

const arr1 = ['d','a','b','c'] ; const arr2 = [{a:1},{c:3},{d:4},{b:2}]; We are required to write a JavaScript function that accepts these two arrays. The function should sort the second array according to the elements of the first array.

Does order of properties in object matter?

The order of properties in an object depends on the type of the included properties and their values. Looking at the spec the rules are defined in the internal "ownPropertyKeys" method. Which is used for example by fairly new methods Object. getOwnPropertyNames and Reflect.


2 Answers

javascript has the sort function which can take another function as parameter - that second function is used to compare two elements.

Example:

cars = [      {         name: "Honda",         speed: 80     },      {         name: "BMW",         speed: 180     },      {         name: "Trabi",         speed: 40     },      {         name: "Ferrari",         speed: 200     } ]   cars.sort(function(a, b) {      return a.speed - b.speed; })  for(var i in cars)     document.writeln(cars[i].name) // Trabi Honda BMW Ferrari  

ok, from your comment i see that you're using the word 'sort' in a wrong sense. In programming "sort" means "put things in a certain order", not "arrange things in groups". The latter is much simpler - this is just how you "sort" things in the real world

  • make two empty arrays ("boxes")
  • for each object in your list, check if it matches the criteria
  • if yes, put it in the first "box"
  • if no, put it in the second "box"
like image 147
user187291 Avatar answered Sep 27 '22 19:09

user187291


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"); 
like image 38
Cheeso Avatar answered Sep 27 '22 21:09

Cheeso