[英]Sort an array of objects in typescript?
How do I sort an array of objects in TypeScript?如何对 TypeScript 中的对象数组进行排序?
Specifically, sort the array objects on one specific attribute, in this case nome
("name") or cognome
("surname")?具体来说,根据一个特定属性对数组对象进行排序,在这种情况下是
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!谢谢!
It depends on what you want to sort.这取决于您要排序的内容。 You have standard sort funtion for Array s in JavaScript and you can write complex conditions dedicated for your objects.
您在 JavaScript 中拥有Array的标准排序功能,并且您可以为您的对象编写专用的复杂条件。 fe
铁
var sortedArray: Test[] = unsortedArray.sort((obj1, obj2) => {
if (obj1.cognome > obj2.cognome) {
return 1;
}
if (obj1.cognome < obj2.cognome) {
return -1;
}
return 0;
});
Simplest way for me is this:对我来说最简单的方法是这样的:
Ascending:上升:
arrayOfObjects.sort((a, b) => (a.propertyToSortBy < b.propertyToSortBy ? -1 : 1));
Descending:降序:
arrayOfObjects.sort((a, b) => (a.propertyToSortBy > b.propertyToSortBy ? -1 : 1));
In your case, Ascending:在您的情况下,升序:
testsSortedByNome = tests.sort((a, b) => (a.nome < b.nome ? -1 : 1));
testsSortedByCognome = tests.sort((a, b) => (a.cognome < b.cognome ? -1 : 1));
Descending:降序:
testsSortedByNome = tests.sort((a, b) => (a.nome > b.nome ? -1 : 1));
testsSortedByCognome = tests.sort((a, b) => (a.cognome > b.cognome ? -1 : 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;
});
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;
}
have you tried sth like this?你试过这样吗?
[{nome:'abc'}, {nome:'stu'}, {nome:'cde'}].sort(function(a, b) {
if (a.nome < b.nome)
return -1;
if (a.nome > b.nome)
return 1;
return 0;
});
you can use this method.你可以使用这个方法。
let sortedArray: Array<ModelItem>;
sortedArray = unsortedArray.slice(0);
sortedArray.sort((left, right) => {
if (left.id < right.id) return -1;
if (left.id > right.id) return 1;
return 0;
})
I am using angular 7 and I tried pipe but didn't work and I tried this and got the output right.我正在使用 angular 7,我尝试了管道但没有用,我尝试了这个并得到了正确的输出。
let array of objects be in object result让对象数组在对象结果中
results:any ={
"providers": [
{
"name": "AAA",
"error": {
"success": true,
"message": "completed"
},
"quote_id": "BA503452VPC0012790",
"quotes": {
"comprehensive": {
"premiumBreakup": {
"premium": "17398.0",
}
},
}
},
{
"name": "Fi",
"error": {
"success": true,
"message": "completed"
},
"quotes": {
"comprehensive": {
"premiumBreakup": {
"premium": "27957.00"
}
},
}
},
]
}
On clicking sort function点击排序功能
<button class="t-sort-optn" (click)="sortByPremium()">Premium</button>
To sort based on the premium value根据溢价排序
sortByPremium(){
var items = this.results.providers;
console.log("Array",items);
items.sort(function (a, b) {
return a.quotes.comprehensive.premiumBreakup.premium - b.quotes.comprehensive.premiumBreakup.premium;
});
console.log("Array Sorted",items)
}
This is how it worked for me这就是它对我的工作方式
.sort((a, b) => {
const a2 = a as unknown as Type;
const b2 = b as unknown as Type;
if (a2.something > b2.something) {
return 1;
}
if (a2.something < b2.something) {
return -1;
}
return 0;
})
You could use a function with a generic type:您可以使用具有泛型类型的函数:
const sortArrayOfObjects = <T>(
data: T[],
keyToSort: keyof T,
direction: 'ascending' | 'descending' | 'none',
) => {
if (direction === 'none') {
return data
}
const compare = (objectA: T, objectB: T) => {
const valueA = objectA[keyToSort]
const valueB = objectB[keyToSort]
if (valueA === valueB) {
return 0
}
if (valueA > valueB) {
return direction === 'ascending' ? 1 : -1
} else {
return direction === 'ascending' ? -1 : 1
}
}
return data.slice().sort(compare)
}
Now if you use the function to sort array of objects, you can specify the object attribute you want to sort by.现在,如果您使用该函数对对象数组进行排序,则可以指定要作为排序依据的对象属性。
const array = [
{ id: 2, name: "name2" },
{ id: 1, name: "name1" },
{ id: 3, name: "name3" }
];
const sortedArray = sortArrayOfObjects(array, "id", "ascending")
console.log(sortedArray)
//sorted ascending by id
// [
// { id: 1, name: "name1" },
// { id: 2, name: "name2" },
// { id: 3, name: "name3" }
// ]
Using generic type and 'keyOf T' as type of attribute helps us to select only available object attributes, in this case, "id" and "name".使用泛型类型和“keyOf T”作为属性类型有助于我们仅选择可用的对象属性,在本例中为“id”和“name”。 typescript helper
打字稿助手
I often need to sort on a single field in a data set result, say Id
and the shortest way of writing that is this我经常需要对数据集结果中的单个字段进行排序,比如
Id
和最短的书写方式就是这样
data.sort((a, b) => a.Id - b.Id)
.forEach(row => {
//something with row
});
var arr = [110,5,72,14,12] var arr = [110,5,72,14,12]
arr.sort(( a, b ) => a > b? 1: -1 ) This will sort arr in ascending order arr.sort(( a, b ) => a > b? 1: -1 ) 这将按升序对 arr 进行排序
arr.sort(( a, b ) => a < b? 1: -1 ) This will sort arr in descending order arr.sort(( a, b ) => a < b? 1: -1 ) 这将按降序对 arr 进行排序
将您的数组视为 myArray,
myArray.sort(( a, b ) => a > b ? 1 : 0 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.