2011-06-02 19 views
6

Hay, tengo una matriz de objetos y debo ordenarlos (ya sea DESC o ASC) por una determinada propiedad de cada objeto.Ordenado una matriz de objetos javascript por una propiedad de objeto

He aquí los datos

obj1 = new Object; 
obj1.date = 1307010000; 

obj2 = new Object; 
obj2.date = 1306923600; 

obj3 = new Object; 
obj3.date = 1298974800; 

obj4 = new Object; 
obj4.date = 1306923600; 

obj5 = new Object; 
obj5.date = 1307096400; 

data = [obj1,obj2,obj3,obj4,obj5]; 

Ahora, quiero ordenar la matriz de datos de manera que los objetos están en orden por fecha.

¿Alguien me puede ayudar con esto?

Respuesta

32

Uso de la matriz sort() método

data.sort(function(a, b){ 
    return a.date - b.date; 
}); 
4

intente esto:

data.sort(function(a,b){ 
    return a.date - b.date; //to reverse b.date-a.date 
}); 
1

Se puede utilizar una función de ordenación:

function mySort(a,b) { 
    return (a.date - b.date); 
} 
data.sort(mySort); 
3

Esta solución funciona con cualquier tipo de datos:

sort_array_by = function(field, reverse, pr){ 
    reverse = (reverse) ? -1 : 1; 
    return function(a,b){ 
    a = a[field]; 
    b = b[field]; 
    if (typeof(pr) != 'undefined'){ 
     a = pr(a); 
     b = pr(b); 
    } 
    if (a<b) return reverse * -1; 
    if (a>b) return reverse * 1; 
    return 0; 
    } 
} 

A continuación, utilizar de esta manera (inverso especie):

data.sort(sort_array_by('date', true, function(a){ 
    return new Date(a); 
})); 

Como otro ejemplo, puede ordenar por una propiedad de tipo "entero":

data.sort(sort_array_by('my_int_property', true, function(a){ 
    return parseInt(a); 
})); 
0

Este es un ejemplo de cómo uso la clasificación matriz de objetos en orden ascendente aquí "matriz" es una pasta gama de object.copy en una etiqueta de script y entender trabajo a través de la consola ...

function OBJECT(){ 
    this.PROPERTY1 =Math.floor(Math.random()*10+1) ; 


} 

OBJECT.prototype.getPROPERTY1=function(){ 
    return(this.PROPERTY1); 
} 
OBJECT.prototype.setPROPERTY1=function (PROPERTY){ 
    this.PROPERTY1=PROPERTY; 
} 

var array= new Array(); 
console.log("unsorted object") 
for(var a=0;a<10;a++) 
{ 
array.push(new OBJECT()); 
console.log(array[a].getPROPERTY1()) 
} 


function sorting() { 
    for(var i in array){ 
     array[i].setPROPERTY1((array[i].getPROPERTY1()*1)) 
      //that is just for sorting an integer value escape this line if not an          
      //integer property 
    } 

    var arr=new(Array); 
    var temp1=new(Array); 
    for(var i in array){ 
     temp1.push(array[i]); 
    } 
    var temporary=new(Array) 
    for(var i in array) 
    { 
     var temp = array[i].getPROPERTY1(); 
     arr.push(temp); 
    } 
    arr.sort(function(a,b){return a-b}); 
    //the argument above is very important 

    console.log(arr) 
    for(var i in arr){ 

     for(var j in temp1) 
      if(arr[i]==temp1[j].getPROPERTY1()) 
       break; 

     temporary.push(temp1[j]) 


     temp1.splice(j,1)//just this statement works for me 

    } 
    array.length=0; 
    for(var i in temporary) 
    { 
     array.push(temporary[i]) 
    } 



} 


    sorting(); 
     console.log("sorted object") 
for(var a=0;a<10;a++) 
{ 
      console.log(array[a].getPROPERTY1()) 
} 
0

Agrego esta respuesta porque veo que este hilo está referenciado al marcar duplicados y algunas soluciones más nuevas y más limpias están disponibles hoy en día.

Otra solución es utilizar una biblioteca de utilidad como Lodash y usar su función Collection#sortBy. Produce un código muy limpio y promueve un estilo de programación más funcional, lo que da como resultado menos errores. En un vistazo queda claro cuál es la intención del código. cuestión

de OP sólo se puede resolver como:

var sortedObjs = _.sortBy(data, 'date'); 

Más información? P.ej. tenemos los siguientes objetos anidados:

var users = [ 
  { 'user': {'name':'fred', 'age': 48}}, 
  { 'user': {'name':'barney', 'age': 36 }}, 
  { 'user': {'name':'fred'}}, 
  { 'user': {'name':'barney', 'age': 21}} 
]; 

Ahora podemos utilizar la abreviatura _.propertyuser.age para especificar la ruta de acceso a la propiedad que debe ser igualada. Ordenaremos los objetos del usuario por la propiedad de edad anidada. Sí, ¡permite la coincidencia de propiedades anidadas!

var sortedObjs = _.sortBy(users, ['user.age']); 

¿Quiere invertir? No hay problema. Use _.reverse.

var sortedObjs = _.reverse(_.sortBy(users, ['user.age'])); 

desea combinar ambos usando Chaining en su lugar?

var sortedObjs = _.chain(users).sortBy('user.age').reverse().value(); 
Cuestiones relacionadas