I would like to display an array of object's properties in a custom sorted order. Here is the initial array:
$scope.weekDays = [
{
"day" : "TUESDAY",
"count": 10
},
{
"day" : "MONDAY",
"count": 20
},
{
"day" : "WEDNESDAY",
"count": 30
},
{
"day" : "SUNDAY",
"count": 60
}];
By default, if we print the days from weekDays
, it will appear as TUESDAY, MONDAY, WEDNESDAY, SUNDAY.
However, I want to display them in a specific order: "SUNDAY", "MONDAY", "FRIDAY", "TUESDAY","WEDNESDAY"
To achieve this, I have implemented the following:
$scope.order = ["SUNDAY", "MONDAY", "FRIDAY", "TUESDAY","WEDNESDAY"];
$scope.sortedArray = [];
$scope.sortCustomOrder = function() {
var index = 0;
for(var i = 0; i < $scope.order.length; i++) {
for (var j = 0; j < $scope.weekDays.length; j++) {
if($scope.weekDays[j].day==$scope.order[i]) {
$scope.sortedArray[index] = $scope.weekDays[j];
index++;
}
}
}
};
After printing $scope.sortedArray
, it displays the desired order.
Are there any simpler or more efficient methods in AngularJS to accomplish this?