How can I check that an array element already exists within cookie?
Here is my code:
var cookieList = function (cookieName) {
var cookie = Cookies.get(cookieName);
var items = cookie ? cookie.split(/,/) : new Array();
return {
"add": function (val) {
items.push(val);
Cookies.set(cookieName, items.join(','), { path: '/' });
}
}
}
var list = new cookieList("MyItems");
$('.items').on('click', '.add', function () {
var imageId = $(this).data("id");
list.add(JSON.stringify(imageId));
});
You can add a method
exists
tocookieList
and then check whether the passed value exists in theitems
array usingArray.indexOf()
Demo: Fiddle