javascript - Sort array of objects by string property value

Mots clés : javascriptarrayssortingcomparisonjavascript

meilleur 5 Réponses javascript - Sort array of objects by string property value

vote vote

93

function compare( a, b ) {   if ( a.last_nom < b.last_nom ){     return -1;   }   if ( a.last_nom > b.last_nom ){     return 1;   }   return 0; }  objs.sort( compare ); 
objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0)) 
vote vote

89

function dynamicSort(property) {     var sortOrder = 1;     if(property[0] === "-") {         sortOrder = -1;         property = property.substr(1);     }     return function (a,b) {         /* next line works with strings and numbers,           * and you may want to customize it to your needs          */         var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;         return result * sortOrder;     } } 
var People = [     {Name: "Name", Surname: "Surname"},     {Name:"AAA", Surname:"ZZZ"},     {Name: "Name", Surname: "AAA"} ]; 
People.sort(dynamicSort("Name")); People.sort(dynamicSort("Surname")); People.sort(dynamicSort("-Surname")); 
function dynamicSortMultiple() {     /*      * save the arguments object as it will be overwritten      * note that arguments object is an array-like object      * consisting of the names of the properties to sort by      */     var props = arguments;     return function (obj1, obj2) {         var i = 0, result = 0, numberOfProperties = props.length;         /* try getting a different result from 0 (equal)          * as long as we have extra properties to compare          */         while(result === 0 && i < numberOfProperties) {             result = dynamicSort(props[i])(obj1, obj2);             i++;         }         return result;     } } 
People.sort(dynamicSortMultiple("Name", "-Surname")); 
class MyArray extends Array {     sortBy(...args) {         return this.sort(dynamicSortMultiple(...args));     } } 
MyArray.from(People).sortBy("Name", "-Surname"); 
vote vote

77

objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom)); 
objs.sort(function(a, b) {     return a.last_nom.localeCompare(b.last_nom) }); 
vote vote

68

var objs = [    { first_nom: 'Lazslo',last_nom: 'Jamf' },   { first_nom: 'Pig', last_nom: 'Bodine'  },   { first_nom: 'Pirate', last_nom: 'Prentice' } ];  var sortedObjs = _.sortBy( objs, 'first_nom' ); 
vote vote

50

obj.sort(function(a,b){   if(a.last_nom< b.last_nom) return -1;   if(a.last_nom >b.last_nom) return 1;   if(a.first_nom< b.first_nom) return -1;   if(a.first_nom >b.first_nom) return 1;   return 0; }); 

Questions similaires