Utilizing an input connected to an API, I can retrieve a list of cities based on the entered letters. The API is triggered with each keyup
event in this manner:
let ville_input = document.getElementById("search_immobilier_ville");
let ville_arr = [];
ville_input.addEventListener("keyup", () => {
res_list.innerHTML = "";
fetch("https://api.fr/communes?nom=" + ville_input.value)
.then(res => {
return res.json();
})
.then(data => {
data.forEach(el => {
if (
el.codeDepartement == "971" &&
el.nom
.toUpperCase()
.startsWith(ville_input.value.toUpperCase().trim())
) {
if (!ville_arr.includes([el.nom, el.codesPostaux[0]])) {
ville_arr.push([el.nom, el.codesPostaux[0]]);
console.log(ville_arr);
}
}
});
})
.catch(err => {
// Performing actions
});
});
To store the results as arrays within another array, my first approach is to push them like so:
ville_arr.push([el.nom, el.codesPostaux[0]])
The problem arises when duplicate items are added to the array due to repetitive API calls fetching the same results. To avoid this issue, I implemented the following check:
if(!ville_arr.includes([el.nom, el.codesPostaux[0]])){
ville_arr.push([el.nom, el.codesPostaux[0]])
console.log(ville_arr)
}
Despite these adjustments, duplicates still persist in the final array. Could it be related to the unique indexes or something else entirely?