Search code examples
javascriptangularjsjsonangularjs-filter

How to Order JSON data in the controller using AngularJS $filter


I have a data array like below in the controller

$scope.sampleArray=[{
    'title': 'SampleTitleOne',
    'description': 'SampleDescriptionOne',
    'category': 'Saving'
},
{
    'title': 'SampleTitleTwo',
    'description': 'SampleDescriptionTwo',
    'category': 'Saving'
},
{
    'title': 'SampleTitle3',
    'description': 'SampleDescription3',
    'category': 'Current'
},
{
    'title': 'SampleTitleIV',
    'description': 'SampleDescriptionIV',
    'category': 'Current'
},
{
    'title': 'SampleTitleFive',
    'description': 'SampleDescriptionFive',
    'category': 'Group'
},
{
    'title': 'SampleTitleFive',
    'description': 'SampleDescriptionFive',
    'category': 'Group'
},
{
    'title': 'SampleTitleFive',
    'description': 'SampleDescriptionFive',
    'category': 'Mixed'
},
{
    'title': 'SampleTitleFive',
    'description': 'SampleDescriptionFive',
    'category': 'Other'
}];

I have order the above array based on user input. Suppose user input array is

$scope.order = ['Other', 'Group', 'Mixed', 'Saving', 'Current'];

After applying the filter the output should be like below

$scope.sampleArray=[{
    'title': 'SampleTitleFive',
    'description': 'SampleDescriptionFive',
    'category': 'Other'
},
{
    'title': 'SampleTitleFive',
    'description': 'SampleDescriptionFive',
    'category': 'Group'
},
{
    'title': 'SampleTitleFive',
    'description': 'SampleDescriptionFive',
    'category': 'Group'
},

{
    'title': 'SampleTitleFive',
    'description': 'SampleDescriptionFive',
    'category': 'Mixed'
},
{
    'title': 'SampleTitleOne',
    'description': 'SampleDescriptionOne',
    'category': 'Saving'
},
{
    'title': 'SampleTitleTwo',
    'description': 'SampleDescriptionTwo',
    'category': 'Saving'
},
{
    'title': 'SampleTitle3',
    'description': 'SampleDescription3',
    'category': 'Current'
},
{
    'title': 'SampleTitleIV',
    'description': 'SampleDescriptionIV',
    'category': 'Current'
}];

Is there any way to apply angular $filter to achieve this?


Solution

  • Use the orderBy filter

    $scope.sampleArray = $filter('orderBy')($scope.sampleArray, function(item) { return $scope.order.indexOf(item.category);});