Sort obserable array - if an object has a specific property set this object first

Discussão em 'Angular' iniciado por Babulaas, Fevereiro 24, 2025.

  1. Babulaas

    Babulaas Guest

    In my my function I have this code to retrieve the list of objects:

    this.personService.getAccountOverview().subscribe(persons => this.personsSubject.next(persons));


    the output wil be

    [
    { name: 'John Doe', age: 44, isCrazy: false, isAnotherLevelCrazy: false, isExtremeCrazy: false },
    { name: 'Jane Doe', age: 28, isCrazy: false, isAnotherLevelCrazy: false, isExtremeCrazy: false },
    { name: 'Crazy Doe', age: 36, isCrazy: true, isAnotherLevelCrazy: false, isExtremeCrazy: false },
    { name: 'Extreme Doe', age: 23, isCrazy: false, isAnotherLevelCrazy: true, isExtremeCrazy: true }
    ]


    What I try to achieve is if any of 3 crazy properties is set to true put this object on top of the list. there can be more object where this is true than place those sorted by name on top of the list.

    so it should be crazy doe, extreme doe, jane doe and than john doe.

    I tried this but I do not get the right results / no sorting. (also I did not started on the name sorting for the top items yet)

    this.personService.getAccountOverview().subscribe(persons => {
    persons.sort((a,b) => {
    if(b.isCrazy || b.isAnotherLevelCrazy || extremeCrazy) {
    return 1;
    }
    });
    this.personsSubject.next(persons)
    });


    Can anyone help me with this

    Continue reading...

Compartilhe esta Página