skip to Main Content

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


  1. function reorderArray(arr: number[], target: number): number[] {
      return arr
        .filter(x => x <= target)
        .sort((a, b) => b - a)
        .concat(arr.filter(x => x > target).sort((a, b) => a - b));
    }
    
    // Example usage:
    const result = reorderArray([2,6,4,8,1,9,3,5,10], 4);
    console.log(result); // Output: [4,3,2,1,5,6,8,9,10]
    
    Login or Signup to reply.
  2. You can do it as follows:

    const sortBasedValue = 7
    this.sortedItems = this.items.sort((a, b) => {
        if (a <= sortBasedValue && b <= sortBasedValue) {
            return b - a;
        } else {
            return a - b;
        }
    });
    

    The sort function takes two elements and decides which one is supposed to go first. In your situation, there are three cases:

    • the two numbers are above the special number: the smallest goes first
    • one number is above the special number, one is below: the smallest goes first
    • both are below: the largest goes first.

    So basically, when both are less than or equal to sortBasedValue, we sort them backwards (expressed as b - a), otherwise we sort them normally (expressed as a - b).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search