Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
Angular sorting and splitting and Array

I apologize in advance if this is a stupid question but Angular and Typescript isn't my forte. I am helping a friend out and can't seem to get past this problem.

I have a players array that contains information like first name and kit colour.All I want to do is sort /group the array by kit color under specific H1 tags.

import { Component, VERSION } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  Players = [
    {
      FirstName: 'Vader',
      KitColour: 'Blue',
    },
    {
      FirstName: 'Darth',
      KitColour: 'Red',
    },
    {
      FirstName: 'Yeeeeet',
      KitColour: 'Red',
    },
    {
      FirstName: 'New',
      KitColour: 'Blue',
    },
  ];
  constructor() {
    this.Players.sort((a, b) => {
      var colorA = a.KitColour.toLowerCase();
      var colorB = b.KitColour.toLowerCase();
      if (colorA < colorB) {
        return -1;
      }
      if (colorA > colorB) {
        return 1;
      }
      return 0;
    });
    const sliceArray = (arr, chunkSize) => {
      const result = [];
      for (let i = 0; i < arr.length; i += chunkSize) {
        const chunk = arr.slice(i, i + chunkSize);
        result.push(chunk);
      }
      return result;
    };
    sliceArray(this.Players, 2);
    console.log(this.Players);
  }
}
<div class="container" *ngFor="let player of Players">
  <!-- <div class="Red" *ngIf="player.KitColour === 'Red'">
    <h1>Red Team</h1>
    <p>{{ player.FirstName }}</p>
  </div>
  <div class="Blue" *ngIf="player.KitColour === 'Blue'">
    <h1>Blue Team</h1>
    {{ player.FirstName }}
  </div> -->
  <div class="{{ player.KitColour }}">
    <h1>{{ player.KitColour }}</h1>
    <p>{{ player.FirstName }}</p>
</div>

My Output: enter image description here

How can I just sort them once under a single H1 tag either Blue or Red depending on Kit Color ? Example: Red Player Names..

Blue Player Names..

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The best way to tackle that would be to rework your object (or in a service or in the component).

groupByKitColor = (array: any) => {
    return array.reduce((prev, actual) => {
      prev[actual.KitColour] = prev[actual.KitColour] || [];
      prev[actual.KitColour].push(actual);
      return prev;
    }, Object.create(null));
  };

This solution will group the players under whatever number of colors you will add in the future. Then, just apply your CSS class.

See attached StackBlitz : https://stackblitz.com/edit/angular-ivy-dyflwe?file=src%2Fapp%2Fapp.component.html

PS: some comments here, you should do your sorting logic in the OnInit Lifecycle and not in the constructor (by convention) and your variables should follow the camelCase convention ;)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Sort array by KitColour property

  Players = [
    {
      FirstName: 'Vader',
      KitColour: 'Blue',
    },
    {
      FirstName: 'Darth',
      KitColour: 'Red',
    },
    {
      FirstName: 'Yeeeeet',
      KitColour: 'Red',
    },
    {
      FirstName: 'New',
      KitColour: 'Blue',
    },
  ].sort((a, b) => a.KitColour.localeCompare(b.KitColour));

and use this html

   <div *ngFor="let player of Players; let index = index">
    <h1 *ngIf="0 === index">{{ player.KitColour }}</h1>
    <h1 *ngIf="0 !== index && player.KitColour! !== Players[index - 1].KitColour">
      {{ player.KitColour }}
    </h1>

    <p>{{ player.FirstName }}</p>
  </div>
about 4 years ago · Juan Pablo Isaza Denunciar

0

Because you're putting the ngFor at the parent div, you'll have as much h1 elemements as the length of the array (one for each element). If you know your colors just extract the color outside of ngFor and then conditionally (with ngIf) display the names

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda