I am currently developing a mobile application using Angular, JavaScript, Ionic, and Cordova.
Within one of my functions, I make use of an array called existingEntries, which is stored as a variable.
categories: Array [276]
[0...99]
0: Object
id: 288
exclude: false
1: Object
id: 320
exclude: true
This function iterates through all elements in the array to check if the 'exclude' value is set to true or false.
var existingEntries = $scope.categoryList;
if(existingEntries == null) existingEntries = [];
for (var i = 0; i < existingEntries.length; i++) {
if (existingEntries[i]['exclude'] == true) {
$scope.addLocalExcludedCategories(i);
} else if (existingEntries[i]['exclude'] == false) {
$scope.removeLocalExcludedCategories(i);
}
}
After this process, other related functions (addLocal.. and remove Local...) are invoked to store the IDs locally. The addLocal.. function is shown below, but it seems to produce duplicates when executed repeatedly. I believe there's room for optimization in the code. I'm currently utilizing local storage for saving the array, but I'm open to exploring alternative solutions.
$scope.addLocalExcludedCategories = function(catID) {
console.log("addLocalExcludedCategories Called")
//Add Item to Excluded Categories Variable
var existingEntries = JSON.parse(window.localStorage.getItem("ExcludedCategories"));
if(existingEntries == null) existingEntries = [];
var entryId = catID;
var entry = {
'id': entryId,
};
existingEntries.push(entry);
window.localStorage.setItem("ExcludedCategories", JSON.stringify(existingEntries));
$scope.ExcludedCategories = window.localStorage.getItem("ExcludedCategories");
}
Below is the remove function, which seems to be having issues identifying IDs with 'exclude' values set to false instead of true.
$scope.removeLocalExcludedCategories = function(catID) {
console.log("removeLocalExcludedCategories Called")
//Remove Item from Excluded Categories Variable
var existingEntries = JSON.parse(window.localStorage.getItem("ExcludedCategories"));
if(existingEntries == null) existingEntries = [];
for (var i = 0; i < existingEntries.length; i++) {
if (existingEntries[i]['id'] == catID) {
console.log(i);
existingEntries.splice(i, 1);
}
}
window.localStorage.setItem("ExcludedCategories", JSON.stringify(existingEntries));
$scope.ExcludedCategories = window.localStorage.getItem("ExcludedCategories");
console.log($scope.ExcludedCategories);
}
I hope this explanation is clear. Thank you in advance for any assistance!