0

I implemented sort in alphabetical order and wanted rearrange the objects (move all status red object to the bottom of the array. How I can move all status red data to end of the array in from my onLoad function?

// sample data
const data = [
  {
    status: "green",
    name: "alex"
  },
  {
    status: "red",
    name: "ken"
  },
  {
    status: "red",
    name: "roy"
  },
  {
    status: "green",
    name: "boy"
  }
]

users: User[];

// get list
onLoad() {
    this.service.getList$
        .pipe(takeUntil(this._unsubscribeAll))
        .subscribe((users: User[]) => {
            this.users = users;
                .sort((a, b) => 0 - (a.name > b.name ? -1 : 1));
        });
}

jabaa
  • 5,844
  • 3
  • 9
  • 30
Johnny
  • 261
  • 7
  • 22
  • Does this answer your question? [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) – jabaa Mar 27 '22 at 18:30
  • Your IDE should mark you some syntax errors in your code. – jabaa Mar 27 '22 at 18:33
  • 1
    Sorting in alphabetical order working, I wanted to implement another operation that move all status `red` to bottom of the list (array). – Johnny Mar 27 '22 at 18:33
  • 1
    First, your code can't work. It contains syntax errors. Second, add a sort function that returns `-1` if only the first argument contains `'red'`, `1` if only the second argument contains `'red'` and otherwise `a.name > b.name ? 1 : -1` – jabaa Mar 27 '22 at 18:37
  • Do u have any example of that? I don't get it – Johnny Mar 27 '22 at 18:46
  • 1
    `if (a.status === 'red' && b.status !== 'red') return 1; if (a.status !== 'red' && b.status === 'red') return -1; return a.name > b.name ? 1 : -1;` – jabaa Mar 27 '22 at 18:48
  • Nice! Thanks @jabaa – Johnny Mar 27 '22 at 18:52

0 Answers0