2013-09-30 16 views
61

Ho questo array. Come utilizzare il carattere di sottolineatura '_.sortBy' per ordinarlo in base alla data di inizio?Matrice con ordinamento di oggetti con Underscore sortBy

[ 
    { 
     id: 'oljw832021kjnb389xzll323jk', 
     start: { dateTime: '2013-09-26T13:30:00-07:00' }, 
     end: { dateTime: '2013-09-26T14:30:00-07:00' }, 
    }, 
    { 
     id: 'ed7l5tmckdp0lm90nvr4is3d4c', 
     start: { dateTime: '2013-09-26T15:30:00-07:00' }, 
     end: { dateTime: '2013-09-26T16:30:00-07:00' }, 
    }, 
    { 
     id: 'etmasdsackdp0kjl0nvrkopioqw', 
     start: { dateTime: '2013-09-26T18:00:00-07:00' }, 
     end: { dateTime: '2013-09-26T19:00:00-07:00' }, 
    } 
] 

risposta

145

Utilizzare una funzione iteratore, non una singola stringa per una proprietà:

_.sortBy(arr, function(o) { return o.start.dateTime; }) 
+0

dà in ordine crescente, ma come ordinarlo in ordine decrescente di data? – Robin

+5

@RobinAT: è possibile annullare il datetime – Bergi

+14

se si desidera eseguire un ordine decrescente, quindi basta arr.reverse() – JrBriones

1

ho fatto in questo modo:

var sorted = _(list).sortBy(
        function (item) {       
         return [new Date(item.effectiveDate).getTime(), item.batchId]; 
        }), "batchId"); 

Se lo vuoi scendere poi è la stessa cosa ma * -1

var sorted = _(list).sortBy(
        function (item) {       
         return [new Date(item.effectiveDate).getTime()*-1, item.batchId]; 
        }), "batchId"); 

I In questo esempio sto ordinando in base a due campi, puoi dimenticarti dell'oggetto item.batchId.

Spero che questo aiuti qualcuno.

Problemi correlati