I would like to sort an array of numbers descending with custom sorting based on a number outside or inside the array in one step without splitting or filtering and reunion
I using Angular 17 and Rxjs 7.8
For example if I have this array of numbers:
items:Array<number>=[2,6,4,8,1,9,3,5,10];
and I want to sort this array based on any number for ex: 7
so expected result will be like
[6,5,4,3,2,1,8,9,10]
another example for number 4 the expected result will be:
[4,3,2,1,5,6,8,9,10]
I tried the following code with no luck
const sortBasedValue = 7
this.sortedItems = this.items.sort((a, b) => {
if (sortBasedValue > b) {
return 1;
}
if (sortBasedValue < b) {
return -1;
}
return 0;
});
So can this custom sorting accomplished in one step?
2
Answers
You can do it as follows:
The sort function takes two elements and decides which one is supposed to go first. In your situation, there are three cases:
So basically, when both are less than or equal to
sortBasedValue
, we sort them backwards (expressed asb - a
), otherwise we sort them normally (expressed asa - b
).