2010-03-17 12 views
50

ho bisogno di fare questo:Javascript elenco oggetti ordinamento per proprietà dell'oggetto

(purtroppo non in JavaScript sintassi-ancora imparando la lingua oggetto :))

oggetto = auto

attibutes: top-velocità , marchio ....

ora voglio ordinare l'elenco di quelle macchine in modo da top-velocità, marca ...

Come faccio a fare questo (si prega di notare la soluzione deve essere javascri solo pt, no php o altre cose)?

+3

@durilai: JavaScript ** ** è orientato agli oggetti, il modello OO di JavaScript si basa su * * Prototyping ed è molto, molto versatile ... http://en.wikipedia.org/wiki/ Prototype-based_programming – CMS

+5

odora di compiti a casa? – Cheeso

+0

Mi raccomando di usare lodash.js: https: // lodash.com/docs # sortBy –

risposta

118

javascript ha la funzione sort che può assumere un'altra funzione come parametro - quella seconda funzione viene utilizzata per confrontare due elementi.

Esempio:

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, dal vostro commento vedo che si sta utilizzando la parola 'tipo' in un senso sbagliato. Programmare "sort" significa "mettere le cose in un certo ordine", non "sistemare le cose in gruppi". Quest'ultimo è molto più semplice - questo è solo come si "Ordina" le cose nel mondo reale

  • fare due array vuota ("scatole")
  • per ogni oggetto nella lista, controllare se corrisponde ai criteri di
  • se sì, metterlo nella prima "scatola"
  • se no, metterlo nella seconda "scatola"
+1

Sembra molto utile, ma non sono sicuro che lo farà, vedete che ho bisogno di seguire questo: (diciamo per esempio) if (ruote <15) { ruote per auto = piccolo; } else { auto-ruote = grande } e di creare 2 nuovi elenchi in base alle dimensioni della ruota – Constructor

+4

nota Semplice per comodità: questo ('a.someProp - b.someProp') le specie da ** più basso al più alto **, e il contrario ('b.someProp - a.someProp') ordina dal più alto al più basso. In sostanza, [se la funzione restituisce meno di 0, viene prima di b.] (Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description) – user568458

14

Esempio.

Viene eseguito su cscript.exe, su 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"); 

È inoltre possibile effettuare una sorter generale.

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"); 
+0

Nice uno. Ma non mi piace annidare le espressioni ternarie, e anche il blocco else non è strettamente necessario dopo un ritorno. – Marcs

+0

Sospetto che tu lo sappia ma per le persone che visualizzano 'nuova macchina (" Chevy "," Corvair ", 1800, 88, 2900)," può anche essere semplicemente "Car (" Chevy "," Corvair ", 1800, 88, 2900), 'senza il' new'. Buona risposta, penso. –

-1

ho scritto questo semplice funzione per me stesso:

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); 
} 

per esempio, si ha la lista delle auto:

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

perché questo commento è votato -2? Penso che questa sia una buona risposta, forse non la più chiara, ma la risposta ancora più dinamica. – wertigom

2

Una versione della soluzione di Cheeso con l'ordinamento inverso, ho anche rimosso le espressioni ternarie per mancanza di chiarezza (ma questo è un gusto personale).

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; 
    }; 
}; 
+0

Buono per l'esempio inverso –

+1

Per essere completamente invertiti i numeri devono essere 'return !! reverse? (a [prop] - b [prop]) * -1: (a [prop] - b [prop]); ' –

+0

Sì, come ora nessun controllo inverso sui numeri, grazie, dovrei sistemarlo. Ma perché il doppio '!' Anche questo va bene: 'return reverse? (a [prop] - b [prop]) * -1: (a [prop] - b [prop]); ' – Marcs

Problemi correlati