I am trying to add past searches to local storage and doing that with an array. The problem is that it adds the value two times, even if there is just one call to the function. For every new, distinct search I want it to be added to my array and storage, if there is more than five, the last item is popped.
Called when a search is processed:
SetLocalStorageItem(searchString[1]);
The function that should do it:
function SetLocalStorageItem(search) {
if(search === '') {
return;
}
console.log(localStorage);
// Check if the browser support Local Storage
if(localStorage) {
if(localStorage["pastSearches"]) {
pastSearches.push(JSON.parse(localStorage["pastSearches"]));
}
// Check if the value exists in the array,
// returns -1 if the array does not contain the value
if($.inArray(search, pastSearches) == -1) {
// If not, put it first and...
pastSearches.unshift(search);
// ...pop one at the end if array is too big
if(pastSearches.length > 5) {
pastSearches.pop();
}
pastSearches.push(search);
// Adding the search to the storage
localStorage["pastSearches"] = JSON.stringify(pastSearches);
DisplayPastSearches();
}
}
}
Function to clear and display:
function ClearSearches() {
// If there is any past searches
localStorage.clear();
pastSearches = [];
}
function DisplayPastSearches() {
if(pastSearches.length) {
$("<div>" + pastSearches + "</div>").appendTo(".container");
}
}
Now, if I clear the searches the array and the storage is empty, and then run the code and searches for "billy", the console.log above prompts:
Storage
length: 1
pastSearches: "["billy","billy"]"
__proto__: Storage