0

I have this code:

results.push(result);
addToLocalStorage(results);

function addToLocalStorage(results) {
  localStorage.setItem("results", JSON.stringify(results));
}

Here is the list that is created when pushing the values:

enter image description here

So when pushing the values, a div with id of country value is created:

<div id="France"></div>
<div id="France"></div>

How can I do to not repeat another div with the same id and to not repeat that when pushing the values to the localStorage? I tried mapping the values of the countries and get the last element also from the array, but that doesn't work. I don't know in which part I am making a mistake

Hello World
  • 207
  • 1
  • 12
  • Before you `.push` the new `result` onto the array, you need to first read localStorage and test to see if `result` is already in the array. – Lil Devil Mar 20 '21 at 00:58
  • Also [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/q/237104/262708) – Lil Devil Mar 20 '21 at 01:00
  • Thank you everyone! I will check those posts, but I'll keep trying also... If any of you have some similar example, it will be very useful. I will see also what @LilDevil said – Hello World Mar 20 '21 at 01:08
  • Do I need to push first to the localStorage so I can compare the country of LocalStorage with the result.country? – Hello World Mar 20 '21 at 01:16

1 Answers1

1

Before pushing new 'result' into the 'results' array, do a check if the value exist in that array. If not make the push and write the new array to local storage.

In the below code 'Brazil' already exist in the array and hence wont be added again.

This way your results array and local storage will hold values without any duplicates.

let results = [{country: 'France'},{country: 'Brazil'},{country: 'Dubai'},{country: 'Ireland'}];
let result = {country: 'Brazil'};
countryExist = results.some(obj => obj.country === result.country);
if (!countryExist) {
  results.push(result);
  addToLocalStorage(results);
}
console.log(results);

function addToLocalStorage(results) {
  localStorage.setItem("results", JSON.stringify(results));
}
Zam Abdul Vahid
  • 2,389
  • 3
  • 18
  • 25
  • Thank you man! This worked like a charm! I realized that my solution was very difficult to understand and it was not working, less is more :) – Hello World Mar 20 '21 at 02:10