0

using $filter in controller to sort list of json data by price and added date, in the json data price is stored as string instead of number. I want to sort them by price first then added date, sample angular code in jsfiddle

http://jsfiddle.net/5wkvzbgt/7/

$scope.results = $filter('orderBy')($scope.results, ['-price','added']);
2
  • 1
    So why you don't convert them to numbers on data get? Commented Jan 23, 2017 at 15:31
  • json data is just sample. i will not aware what json data i get from backend. json columns may change also Commented Jan 23, 2017 at 15:33

1 Answer 1

2

You can pass a function to your expression argument and use it to parse the string to a number. Setting the 3rd parameter to true reverse the results:

$scope.results = $filter('orderBy')($scope.results, 
                             [function(a){ return parseInt(a.price); },'-added']);

See updated fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

Looks good, but doesnt work when sort 'price' as asc and 'added' as desc.
Sorry, you want to sort by price 'asc' and added 'desc'?
Thanks, is it possible to do desc sort using the function? i mean for string is it possible to sort desc with the function?

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.