2017-04-09 99 views
-1

如何在TypeScript中對一組對象進行排序?對打字稿中的對象數組進行排序?

具體來說,對一個特定屬性(本例中爲nome(「name」)或cognome(「surname」))排列數組對象?

/* Object Class*/ 
export class Test{ 
    nome:String; 
    cognome:String; 
} 

/* Generic Component.ts*/ 
tests:Test[]; 
test1:Test; 
test2:Test; 

this.test1.nome='Andrea'; 
this.test2.nome='Marizo'; 
this.test1.cognome='Rossi'; 
this.test2.cognome='Verdi'; 

this.tests.push(this.test2); 
this.tests.push(this.test1); 

thx!

+2

你試過了什麼?請顯示您嘗試過的代碼,並且我們可以建議如何解決它。 – RJM

回答

2

這取決於你想要排序。你有標準的排序函數數組 s在JavaScript中,你可以編寫專用於你的對象的複雜條件。 f.e

var sortedArray: Test[] = unsortedArray.sort((obj1, obj2) => { 
    if (obj1.cognome > obj2.cognome) { 
     return 1; 
    } 

    if (obj1.cognome < obj2.cognome) { 
     return -1; 
    } 

    return 0; 
}); 
+0

這只是一個小例子,我的數組由不少於20個元素組成 –

+0

我想你不理解函數作爲排序方法的參數傳遞。該函數總是有兩個參數(數組中的對象是相同的類型),它顯示瞭如何對數組進行排序。在我的例子中,數組的大小並不重要。數組可能有兩個或一千個元素。排序將由每個函數比較元素(obj1,obj2)=> {//比較} –

2
this.tests.sort(t1,t2)=>(t1:Test,t2:Test) => { 
    if (t1.nome > t2.nome) { 
     return 1; 
    } 

    if (t1.nome < t2.nome) { 
     return -1; 
    } 

    return 0; 
} 

你嘗試過某事像這樣?

+0

如何實現一些通用的操作,因爲我的數組大小會週期性變化? –

+0

它排序所有列表,如果列表大小發生變化,排序的數組大小也會改變 – coenni

-1
const sorted = unsortedArray.sort((t1, t2) => { 
     const name1 = t1.name.toLowerCase(); 
     const name2 = t2.name.toLowerCase(); 
     if (name1 > name2) { return 1; } 
     if (name1 < name2) { return -1; } 
     return 0; 
    });