My current challenge involves sorting an array of objects alphabetically, and to simplify things, I have provided the example below. In my TypeScript code, I utilize splice to add and remove items from the object array.
Array
cars = [{
id: 1,
items: [{
name: 'car1',
description: 'this is car1 description'
},{
name: 'car2',
description: 'this is car2 description'
},{
name: 'car3',
description: 'this is car3 description'
},{
name: 'car4',
description: 'this is car4 description'
},{
name: 'car5',
description: 'this is car5 description'
}]
}];
html
<p-dataView [value]="cars" [paginator]="true" [rows]="5">
<p-header>List of Cars</p-header>
<p-footer>Choose from the list.</p-footer>
<ng-template let-car pTemplate="listItem">
<p-fieldset legend="Header" *ngIf="car.id === 1" [toggleable]="true">
<div *ngFor="let _car of car.items">
{{_car.name}} - {{_car.description}}
</div>
</p-fieldset>
</ng-template>
</p-dataView>
**********************************************UPDATE******************************** I apologize for the oversight, there is one more layer within the structure.
cars = [{
id: 1,
items: [{
Model:[{
name: 'car1',
description: 'this is car1 description'
}],
Model:[{
name: 'car2',
description: 'this is car2 description'
}],
},
id:2,
items: [{
Model:[{
name: 'car13,
description: 'this is car3 description'
}],
Model:[{
name: 'car4',
description: 'this is car4 description'
}],
}]
}];
I attempted
cars[0].items.Model.sort((a,b) => a[0].name > b[0].name ? 1 : -1) //It did not work
also tried
cars[0].items.Model.sort(function (a, b) {
var nameA = a.name.toLowerCase();
var nameB = b.name.toLowerCase();
if (nameA < nameB) //sort string ascending
return -1
})