Угловая сортировка чисел по функции переключения - PullRequest
0 голосов
/ 20 октября 2018

Итак, что я пытаюсь здесь сделать, это отсортировать числа «2», «20», «3», «30», «21» в правильном порядке: от возрастающего к убывающему, вроде функции переключения.

Однако похоже, что он заказывает от 30 3 21 20 2 и при повторном нажатии функциональной кнопки: 2 20 21 3 30 Сортировка

Код:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  isAscendic = true
   fruits: any = ["2", "20", "3", "30", "21", ];





 <ul>
      <li *ngFor="let fruit of fruits">{{fruit}}
      </li>
    </ul>

    <button (click)="send()">Sort </button>

Ответы [ 3 ]

0 голосов
/ 20 октября 2018

Issue

Вы сравниваете строковое значение с компаратором > и <.Это будет иметь другое значение для строкового значения.

Fix

Очень просто преобразовать строковое значение в число, добавив оператор +.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  isAscendic = true
   fruits: any = ["2", "20", "3", "30", "21", ];

   send(){
     this.isAscendic?this.ascendic():this.descendic()
   }

  ascendic(){
    this.isAscendic = false;
     this.fruits = this.fruits.sort((a1,a2) => {
    if (+a1 < +a2) {
        return 1;
    }
    if (+a1 > +a2) {
        return -1;
    }
    return 0;
});
  }

  descendic(){
    this.isAscendic = true
  this.fruits = this.fruits.sort((a1,a2) => {
    if (+a1 > +a2) {
        return 1;
    }
    if (+a1 < +a2) {
        return -1;
    }
    return 0;
});
  }

  de
}

Рабочая копия здесь - https://stackblitz.com/edit/angular-6fwmpn

0 голосов
/ 20 октября 2018

При использовании строк вы можете преобразовать значения в число и принять дельту в качестве результата для сортировки.

this.fruits = this.fruits.sort((a, b) => +a - +b); // asc
this.fruits = this.fruits.sort((a, b) => +b - +a); // desc
0 голосов
/ 20 октября 2018

Вы имеете дело с числами , а не со строками.Вместо этого вы сравниваете строки, поэтому сначала вам нужно привести их к числам:

if (+a1 < +a2) {
  //^---- note the + on both a1 and a2.
    return 1;
}
if (+a1 > +a2) {
    return -1;
}

Обновлен (работает) стек стека:

https://stackblitz.com/edit/angular-hzfjd7?file=src/app/app.component.ts


Другой возможный подход - сначала отобразить элементы и использовать вместо них сопоставленный массив.

  protected get numericFruits() {
    return this.fruits.map(i => Number(i));
  }

Затем используйте numericFruits вместо fruits.

Полныйкод:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  isAscendic = true
   fruits: any = ["2", "20", "3", "30", "21", ];

   send(){
     this.isAscendic?this.ascendic():this.descendic()
   }

  protected get numericFruits() {
    return this.fruits.map(i => Number(i));
  }

  ascendic(){
    this.isAscendic = false;
     this.fruits = this.numericFruits.sort((a1,a2) => {
        if (a1 < a2) {
            return 1;
        }
        if (a1 > a2) {
            return -1;
        }
        return 0;
    });
  }

  descendic(){
    this.isAscendic = true
  this.fruits = this.numericFruits.sort((a1,a2) => {
    if (a1 > a2) {
        return 1;
    }
    if (a1 < a2) {
        return -1;
    }
    return 0;
});
  }
}

рабочий стекблиц:

https://stackblitz.com/edit/angular-f5ox91?file=src/app/app.component.ts

...