Reputation: 3272
Angular application. I am sorting an array into a *ngFor
to loop through the results to display in sorted order.
So the question isn't just a simple sort by numeric value. I have a list of users in an Array. Each user has a sortId
of a number value, that's straightforward. e.g.
this.users.sort((a, b) => a.sortId - b.sortId);
this will give me a result like:
Row 1 - Sort ID: null - original array position: 7
Row 2 - Sort ID: 1 - original array position: 4
Row 3 - Sort ID: 2 - original array position: 1
Row 4 - Sort ID: 3 - original array position: 3
Row 5 - Sort ID: 4 - original array position: 6
Row 6 - Sort ID: 5 - original array position: 8
Row 7 - Sort ID: 6 - original array position: 5
Row 8 - Sort ID: 7 - original array position: 2
However, I want to deal with null
values by just skipping over them, maintain the their position of the original array - so the null
above will be in the row 7(as its original array position was 7), regardless of whether there is a sortId
of 7 already. SortId: 7
will just go into row 8.
Expected result:
Row 1 - Sort ID: 1 - original array position: 4
Row 2 - Sort ID: 2 - original array position: 1
Row 3 - Sort ID: 3 - original array position: 3
Row 4 - Sort ID: 4 - original array position: 6
Row 5 - Sort ID: 5 - original array position: 8
Row 6 - Sort ID: 6 - original array position: 5
Row 7 - Sort ID: null - original array position: 7
Row 8 - Sort ID: 7 - original array position: 2
Field of users: (the arrayPosition property is just added for demo purposes, so can't be used.)
users = [
{
user: 'fred',
arrayPosition: 1,
sortId: 2
},
{
user: 'Gen',
arrayPosition: 2,
sortId: 7
},
{
user: 'Billy',
arrayPosition: 3,
sortId: 3
},
{
user: 'Sid',
arrayPosition: 4,
sortId: 1
},
{
user: 'James',
arrayPosition: 5,
sortId: 6
},
{
user: 'Tom',
arrayPosition: 6,
sortId: 4
},
{
user: 'Jim',
arrayPosition: 7,
sortId: null
},
{
user: 'Steve',
arrayPosition: 8,
sortId: 5
}
];
I have got it working only when the sortId
was lower than the original array position, otherwise it goes out of order:
this.users.forEach(x => {
this.fieldsList.splice(x['sortId'] - 1, 0, x);
});
please help me and take a look at the stackBlitz example.
Upvotes: 0
Views: 195
Reputation: 595
solved this by sorting all non null values and then adding null in correct indices
this.fieldsList = this.users
.filter(x => x.sortId)
.sort((a, b) => a.sortId - b.sortId);
this.users.forEach((x, i) => {
if (x.sortId === null) this.fieldsList.splice(i, 0, x);
});
https://stackblitz.com/edit/sorting-n2gfvg?file=src/app/app.component.ts
Upvotes: 1