Reputation: 885
Implementing the multiple sort functionality; Where need to toggle the array which hold the sorting fieldname and sorting order;
Example
Click Sort By Name:
[{"sortKey":"name","sortValue":"desc"}]
Again Click Sort By Name:
[{"sortKey":"name","sortValue":"asc"}]
Click Sort By Age:
[{"sortKey":"name","sortValue":"asc"},{"sortKey":"age","sortValue":"desc"} ]
Again Click Sort By Name:
[{"sortKey":"name","sortValue":"desc"},{"sortKey":"age","sortValue":"desc"} ]
if (checkIfObjectExists($scope.sortList, sortingObject)) {
if (!$scope.sortList.hasOwnProperty(sortingObject.sortType)) {
console.log($scope.sortList);
// replace the value for the key
}
} else {
$scope.sortList.push(sortingObject);
}
Upvotes: 0
Views: 74
Reputation: 25892
I changed some things in your implementation. Problem was you were checking if the whole object is not same then push in the array. But what you need if sorKey
is same reverse the sortValue
.
Changed your function checkIfObjectExists
to updateArray
.
function updateArray(array, newObject) {
var i = 0;
for (i = 0; i < array.length; i++) {
var object = array[i];
if (object.sortKey == newObject.sortKey) {
object.sortValue= (object.sortValue==='asc')?'desc':'asc';
return;
}
}
array.push(newObject);
}
And while calling I will just call like this in $scope.clickMe
.
updateArray($scope.sortList, sortingObject);
Upvotes: 1