Home > Software design >  Sorting a array. Help me to understand
Sorting a array. Help me to understand

Time:02-16

im new in javaScript and i need to understand why my array is not sorting in alphabetic order.

Probably im missing something. Somebody can help me?

This is my TS

  getEmpresas() {

this.empresaService.getAll().subscribe({
  next: empresas => this.empresas = empresas,
  error: err => console.log(err),
});
let empresas = this.empresas.filter(obj => obj?.nome.toLowerCase());
empresas.sort(function (a, b) {
  if (a.nome < b.nome) { return -1; }
  if (a.nome > b.nome) { return 1; }
  return 0;

})
return empresas;

}

sry i paste a wrong one.

and here the class Empresa

  export class Empresa {
  id: number;
  nome: string;
  nomeCurto: string;
  inscricaoEstadual: string;
  inscricaoMunicipal: string;
  cnpj: string;
  telefone: string;
  email: string;
  caminhoLogoTipo: string;
}

CodePudding user response:

A subscription is asynchronous. This means the line this.empresas = empresas will not be executed before your sorting function. Just put your sorting call inside the subscription, and don't bother returning a value. this.emprasas will be populated and sorted after receiving a response from your service.

Also, I believe you are trying to convert all names to lower case with filter. This is not what filter does, I've exchanged this line with a call to map that will convert all names to lower case.

  getEmpresas() {
    this.empresaService.getAll().subscribe({
      next: (empresas) => {
        empresas = this.empresas.map((obj) => {
          return { ...obj, nome: obj?.nome.toLowerCase() };
        });
        empresas.sort(function (a, b) {
          if (a.nome < b.nome) return -1;
          if (a.nome > b.nome) return 1;
          return 0;
        });
        this.empresas = empresas;
      },
      error: (err) => console.log(err),
    });
  }

CodePudding user response:

Try this:

getEmpresas() {
    this.empresaService.getAll().subscribe({
      next: (empresas) => {
        empresas = this.empresas.map((obj) => {
          return { ...obj, nome: obj?.nome.toLowerCase() };
        });
        empresas.sort((a,b) => (a.nome > b.nome) ? 1 : ((b.nome > a.nome) ? -1 : 0))
        this.empresas = empresas;
      },
      error: (err) => console.log(err),
    });
  }
  • Related