I save in localstorage an array:

var myLikes = []; myLikes[0] = {'slide':slide_id} localStorage.setItem("myCollection", JSON.stringify(myLikes)); 

Next, I need to check whether the new value is unique and if not, add it to the myCollection array. I'm trying to do it like this:

 var slide_id = $$('#likes').attr('slide_id'); var arrayLikes = JSON.parse(localStorage.getItem('myCollection')); for (var i = 0; i < arrayLikes.length; i++) { if (slide_id == arrayLikes[i].slide) { // dublicate console.log('Dublicate'); } else { console.log('New' + arrayLikes[i].slide); arrayLikes.push({'slide':slide_id}); localStorage.setItem("myCollection", JSON.stringify(arrayLikes)); } } 

As a result, the check does not work and all values ​​are added to localstorage, including duplicates + array begins to increase exponentially.

What am I doing wrong and how can I correctly perform the check?

    2 answers 2

     var slide_id = $('#likes').attr('slide_id'); var arrayLikes = JSON.parse(localStorage.getItem('myCollection')); var found = false; for (var i = 0; i < arrayLikes.length; i++) { if (slide_id == arrayLikes[i].slide) { // dublicate found = true; break; } } if (found) { console.log('Dublicate'); } else { console.log('New' + arrayLikes[i].slide); arrayLikes.push({ 'slide': slide_id }); localStorage.setItem("myCollection", JSON.stringify(arrayLikes)); } 

      The object approach would greatly simplify this task.
      For example, you can inherit from Array :

       class MyLikes extends Array { constructor(storageKey) { super(); Object.assign(this, JSON.parse(localStorage.getItem(storageKey) || '[]')); } findLikeIdx(likeObj) { return this.findIndex(o => o.slide == likeObj.slide); } addLike(likeObj) { const idx = this.findLikeIdx(likeObj); return (idx >= 0) ? idx : this.push(likeObj) - 1; } store(storageKey) { localStorage.setItem(storageKey, JSON.stringify(this)); } } const stKey = 'myCollection', const likes = new MyLikes(stKey); // создание экземпляра объекта и чтение данных из localStorage /* ... */ likes.addLike({ slide: slide_id }); // добавление без дубликатов /* ... */ likes.store(stKey); // запись в localStorage 

      🔷 Демо в JSbin ‎