Skip to content
the poor coder

angular key value pipe compareFn example

Poor Man
Published
Reading time
1 min read

Angular KeyValue Pipe CompareFn Example#

When working with Angular, we often need to manipulate data in various ways, including sorting and filtering. The Angular KeyValue pipe is a useful tool for sorting and filtering data based on key-value pairs.

One of the features of the KeyValue pipe is the ability to provide a compare function to determine the order of the items in the output. By default, the KeyValue pipe sorts based on the keys of the input object. However, we may want to sort based on the values or on some other custom logic.

Example#

Suppose we have an object of fruits and their quantities:

Text


fruits = {apple: 10, banana: 5, orange: 20}

We want to sort the fruits based on their quantity in descending order. To do this, we can use the KeyValue pipe with a custom compare function:

Text


<div *ngFor="let fruit of fruits | keyvalue: sortByQuantity">
  {{fruit.key}}: {{fruit.value}}
</div>

sortByQuantity(a: KeyValue<string, any>, b: KeyValue<string, any>): number {
  return b.value - a.value;
}

In this example, we define a function called sortByQuantity that takes two parameters of type KeyValue. The function returns a number that represents the order of the two items.

The function simply subtracts the value of b from the value of a, which sorts in descending order. If we wanted to sort in ascending order, we would swap a and b in the function.

We then use the KeyValue pipe in our ngFor loop and pass in the sortByQuantity function as the compare function.

And that's how you can use the Angular KeyValue Pipe CompareFn Example to easily sort and display data in your Angular app.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC