orderBy multiple fields in Angular
Please see this:
http://jsfiddle.net/JSWorld/Hp4W7/32/
<div ng-repeat="division in divisions | orderBy:['group','sub']">{{division.group}}-{{division.sub}}</div>
How to Sort multiple fields in Angular 8
You can create a new customSortFunction:
function customSortFunction(arr, sortField, direction){
return arr.sort((a,b)=>{
if(isNaN(a[sortField])){ // compare strings
return a[sortField].localeCompare(b[sortField]) * direction;
}else{// compare numbers
// you can also do a parseInt() here in case of the field value is "123"
return (a[sortField] - b[sortField]) * direction ;
}
}) ;
}
And call this function in yours. Somethink like this:
sortData() {
const sort = this.orLosstreeSortingForm.controls['sortBy'].value;
const orderBy = this.orLosstreeSortingForm.controls['orderBy'].value;
const direction = orderBy === 'A-Z' ? 1 : -1;
const sortField={
'SKU':'skuDescription',
'Planned':'plannedVolume',
'Actual':'actualVolume',
'Variation':'variance',
'OR%':'or'
};
const sortedArray = this.customSortFunction(
this.setDataResponse.factORLossTree,
sortField[sort],
direction);
}
AngularJS orderBy - Multiple fields, but only one reversed
I would use a custom function filter, like this:
<span ng-repeat="sel in pot.sels | orderBy:[orderScore,'name']">
Where the js is something like this:
angular.module('yourModule').controller('MyCtrl',['$scope',function($scope){
$scope.orderScore = function(el){
return (isReverse() ? '-' : '+') + el.score;
}
}]);
I didn't tested this, but is to show you the idea, I need only to find a way to return something that can be ordered with <, === and >
Angular ng-repeat orderBy multiple fields as one field
Add a function like this to your controller:
$scope.sortByEitherDate = function(row) {
if (row.actualStartDate) {
return row.actualStartDate;
}
return row.estimatedStartDate;
}
Then order by it with orderBy:sortByEitherDate
working fiddle: http://jsfiddle.net/g201tudg/4/
Angular 4 - Pipe Orderby Multiple Fields
Edit: following @JBNizet's comment, created a pipe is actually not the preferred way to go if you have many objects, due to performance reasons.
(https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe)
So if you've got many objects, you could filter them in your ts code, not in template.
array.sort((a: any, b: any) => {
if (!a.last.localeCompare(b.last))
{
return a.first.localeCompare(b.first);
}
return a.last.localeCompare(b.last);
});
Original answer
Creating a pipe is indeed a good solution
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sortwithName'
})
export class SortPipe implements PipeTransform {
transform(array: any[], field: string): any[] {
array.sort((a: any, b: any) => {
if (!a.last.localeCompare(b.last))
{
return a.first.localeCompare(b.first);
}
return a.last.localeCompare(b.last);
});
return array;
}
}
https://stackblitz.com/edit/angular-filter-1svqdn?file=app/sortFilterPipe.ts
orderBy two fields (one in reverse)
Change the orderBy
filter to this:
orderBy:['-status','name']
This will order by descending status (by prefixing the -
character), then ascending name. Currently you're passing true
to reverse the sort, which is causing the status to be correct (online first), but the names to be reversed (i.e., descending).
If you want to keep the reverse boolean, you could use orderBy:['status','-name']:true
but that seems less clear than just making status
descending as shown earlier.
orderBy multiple fields in Angular when dropdown is selected
Specify your different options in your controller, it will run smoothly this way. I don't think value
property of option
can contains object of any sort.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.options = [{ label: "id", value: "id" }, { label: "-id", value: "-id" }, { label: "country", value: "country" }, { label: "address", value: "address" }, { label: "country, -id", value: ["country", "-id"] }, { label: "-country, address", value: ["-country", "address"] }];
// all countries $scope.details = [{ id: 1, country: 'Finland', address: 'Mainstreet 2' }, { id: 2, country: 'Mexico', address: 'Some address 1' }, { id: 3, country: 'Canada', address: 'Snowroad 45' }, { id: 4, country: 'Finland', address: 'Rainbow 12' }, { id: 5, country: 'Canada', address: 'Beverly 15' }, { id: 6, country: 'Mexico', address: 'Some address 3' }];});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script><!DOCTYPE html><html ng-app="plunker">
<head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script> document.write('<base href="' + document.location + '" />'); </script> <link href="style.css" rel="stylesheet" /> <script data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js" data-require="angular.js@1.4.x"></script> <script src="app.js"></script></head>
<body ng-controller="MainCtrl"> <div> <label>Country filter</label> <input type="text" ng-model="countryFilter" />
<label>Order by</label> <select ng-model="selectedOrder" ng-options="option.label for option in options">
</select> </div> <ul> <li ng-repeat="detail in details | filter:{country: countryFilter} | orderBy:selectedOrder.value">{{ detail }}</li> </ul></body>
</html>
Related Topics
How to Sort/Order Keys in JavaScript Objects
What Does Document.Domain = Document.Domain Do
Group by Array and Add Field and Sub Array in Main Array
Jquery Get Values of Checked Checkboxes into Array
Understanding React-Redux and Mapstatetoprops()
React - How to Force a Function Component to Render
Convert MySQL Datetime Stamp into JavaScript's Date Format
Vue V-On:Click Does Not Work on Component
Differencebetween Unary Plus/Number(X) and Parsefloat(X)
JavaScript Replace with Reference to Matched Group
Passing Variables to the Next Middleware Using Next() in Express.Js
Google Chromecast Sender Error If Chromecast Extension Is Not Installed or Using Incognito
Creating a JavaScript Cookie on a Domain and Reading It Across Sub Domains
What Is the $$ (Double Dollar Sign) Used for in Angular
Logging Clientside JavaScript Errors on Server
Replace a String in a File with Nodejs
JavaScript Design Pattern: Difference Between Module Pattern and Revealing Module Pattern