1

This is my json:

{
   {
    "FirstName": "Adam" ,
    "Order": 3
   },
   {
    "FirstName": "Baron" ,
    "Order": 1
   },
   {
    "FirstName": "Ashton" ,
    "Order": 4
   },
   {
    "FirstName": "Kara" ,
    "Order": 2
   }
}

I want to order this based on "Order" value. My hunt did not get me anything efficient.

3 Answers 3

2
var people = [
   {
    "FirstName": "Adam" ,
    "Order": 3
   },
   {
    "FirstName": "Baron" ,
    "Order": 1
   },
   {
    "FirstName": "Ashton" ,
    "Order": 4
   },
   {
    "FirstName": "Kara" ,
    "Order": 2
   }
];
function sortJSON(data, key) {
    return data.sort(function (a, b) {
        var x = a[key];
        var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

var people2 = sortJSON(people, 'Order');
console.log("JSON",JSON.stringify(people2));
Sign up to request clarification or add additional context in comments.

Comments

2

You can use pipe, Sorting

*ngFor="let option of options | orderBy:'Order'"

1 Comment

I voted down, because in the same documentation link you provided it is clearly stated that you should not use pipes for sorting: "This isn't an oversight. Angular doesn't offer such pipes because they perform poorly and prevent aggressive minification. Both filter and orderBy require parameters that reference object properties."
1

You could also do this with Lodash:

import * as _ from 'lodash';

_.sortBy(people, p => p.Order);

The advantage is that is also comes with a lot more functionality that can be very handy. Just be mindful of what you import from it, so not to bloat your output bundle.

Don't use pipes for sorting. Snippet from the Pipes documentation:

Appendix: No FilterPipe or OrderByPipe

Angular doesn't provide pipes for filtering or sorting lists. Developers familiar with AngularJS know these as filter and orderBy. There are no equivalents in Angular.

This isn't an oversight. Angular doesn't offer such pipes because they perform poorly and prevent aggressive minification. Both filter and orderBy require parameters that reference object properties. Earlier in this page, you learned that such pipes must be impure and that Angular calls impure pipes in almost every change-detection cycle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.