• Skip to main content
  • Skip to primary sidebar

Web Development Archive

  • Archive
You are here: Home / Other / OrderBy Pipe

OrderBy Pipe

ng g p orderby --skip-import

Pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'orderBy',
  standalone: true,
})
export class OrderByPipe implements PipeTransform {
  transform(array: any[], direction = 'asc', field?: string): any[] {
    if (!Array.isArray(array)) {
      return array;
    }

    let sortedArray: any[] = [];

    if (field) {
      // Ha van mező (field) megadva
      sortedArray = array.sort((a, b) => (a[field] > b[field] ? 1 : -1));
    } else {
      sortedArray = array.sort(); // Ha nincs mező megadva, egyszerűen rendezzük az elemeket
    }

    if (direction === 'desc') {
      return sortedArray.reverse();
    }
    return sortedArray;
  }
}

Component

import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { OrderByPipe } from 'src/app/pipes/orderby.pipe';

@Component({
  standalone: true,
  imports: [OrderByPipe, CommonModule],
  selector: 'app-pipe',
  templateUrl: './pipe.component.html',
  styleUrls: ['./pipe.component.scss'],
})
export class PipeComponent {
  itemsArray1 = ['Banana', 'Apple', 'Orange', 'Strawberry', 'Blueberry', 'Raspberry', 'Ananas', 'Avocado'];
  itemsArray2 = ['Banana', 'Apple', 'Orange', 'Strawberry', 'Blueberry', 'Raspberry', 'Ananas', 'Avocado'];
  itemsArray3 = ['Banana', 'Apple', 'Orange', 'Strawberry', 'Blueberry', 'Raspberry', 'Ananas', 'Avocado'];
}
<h2>OrderBy</h2>
    <article class="grid-3">
      <div>
        <h3>Rendezettlen tömb</h3>
        <ul class="list-group">
          <li class="list-group-item" *ngFor="let item of itemsArray1">{{ item }}</li>
        </ul>
      </div>
      <div>
        <h3>Növekvő sorrend</h3>

        <ul class="list-group">
          <li class="list-group-item" *ngFor="let item of itemsArray2 | orderBy : 'asc'">{{ item }}</li>
        </ul>
      </div>

      <div>
        <h3>Csökkenő sorrend</h3>

        <ul class="list-group">
          <li class="list-group-item" *ngFor="let item of itemsArray3 | orderBy : 'desc'">{{ item }}</li>
        </ul>
      </div>
    </article>

Filed Under: Other

About Gabor Flamich

I'm a web developer and designer based in Budapest, Hungary. In recent years, I've documented hundreds of solutions I came across during development. This site is an archive for useful code snippets on WordPress, Genesis Framework and WooCommerce. If You have any questions related to WordPress development, get in touch!

Primary Sidebar

  • angular.io
© 2026 WP Flames - All Right Reserved