JavaScript issue on using Array.includes() and test duplicate items

javascript check for duplicate entries
how to find duplicate values in array of objects using javascript
how to find duplicate values in array using javascript
how to check if an array has duplicate values in javascript
javascript remove duplicates from array
es6 check for duplicates in array
javascript array check duplicate before push
javascript array contains

I have an input that uses an API to fetch some cities based on the letters inserted. The API is launched on each keyup event like so :

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 => {
      // Doing stuff
    });
});

First of all I want to push each results as arrays into an array like so :

ville_arr.push([el.nom,el.codesPostaux[0]])

My issue is that I get duplicate items into my array when the API fetch the same result, that is why I tried this :

if(!ville_arr.includes([el.nom,el.codesPostaux[0]])){

    ville_arr.push([el.nom,el.codesPostaux[0]])
    console.log(ville_arr)

      }

But I still get duplicate items in the end, I guess it has something to do with the indexes of the array which are unique ? maybe something else ?


Try this:

const 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 => {

            // Clear old data if get new response
            ville_arr = [];

            return res.json();
        })
        .then(...)
        .catch(...);
});

OR try use Array.prototype.find() (and extra info about find vs some on jsPerf.com):

if(!ville_arr.find(i => i[1] === el.codesPostaux[0])) {

    ville_arr.push([el.nom, el.codesPostaux[0]]);
    console.log(ville_arr);
}

Check if an array contains duplicate values, I wanted to write a javascript function which checks if array contains duplicate values or not. If you do this a lot, and the arrays are large, you might want to investigate the possibility of sorting the array and then only comparing adjacent elements. Anyways, my problem is solved. Without a for loop , only using Map() . Definition and Usage. The includes() method determines whether an array contains a specified element. This method returns true if the array contains the element, and false if not.


Array.prototype.includes does a referential equality check for objects.

This means that, even though you are pushing objects of the same shape, they are not the same references because each request creates a new object.

The usual pattern is to remember some uniquely identifying part of an object instead, like an id.

Maybe you can store and check for the zipcode instead?

if (!zipcodes.includes(el.codesPostaux[0])) {
  zipcodes.push(el.codesPostaux[0]);
  ville_arr.push([el.nom, el.codesPostaux[0]]);
}

A time-efficient method is to use a set of zipcodes instead of an array (because set lookup time is O(1)):

if (!zipcodesSet.has(el.codesPostaux[0])) {
  zipcodesSet.add(el.codesPostaux[0]);
  ville_arr.push([el.nom, el.codesPostaux[0]]);
}

If you decide to use the ville_arr only, then what you need could also be done using Array.prototype.every (or Array.prototype.some):

// this will return true if every place in ville_arr
// does not have the zipcode from the response
if (ville_arr.every(([, zipcode]) => zipcode !== el.codesPostaux[0])) {
  ville_arr.push([el.nom, el.codesPostaux[0]]);
}

You could also potentially call JSON.stringify over your object to create the same string from a certain object and save that which would work because includes does equality comparison for primitive values such as strings.

Check if an array contains duplicates in JavaScript, Check if an array contains duplicates in JavaScript. Using ES6 Set. The Set object, introduced in the ES6, can be used to remove duplicate values from an array. The idea is to convert the array to a Set. Underscore/Lodash. In you don't want to use Set as an intermediate data structure, we can use uniq() method from In this quick tutorial, you’ll learn how to find duplicates in an array using JavaScript. For finding duplicate values in JavaScript array, you’ll make use of the traditional for loops and Array reduce method. Using For Loop Let’s see how you can find duplicates in an array using for loop. The logic is you’ll separate the array into two array, duplicate array and unique array. You’ll


Array#includes does not compare reference types by their values; it compares them to check whether their references are the same.

For example, this produces false:

var myArr = [[5, 6], [1, 2], [4, 5]];

console.log(myArr.includes([1, 2]));  // false

Javascript return duplicates from array, If you Simply merging of the array contains duplicates items. Here we use another built-in method of JavaScript arrays, indexOf() that returns the Example​:Yesterday I ran into a programming problem and I didn't like any of the solutions I came up with. Existence check with objects: sets under the hood — Code with Hugo  fromIndex Optional The position in this array at which to begin searching for valueToFind. The first character to be searched is found at fromIndex for positive values of fromIndex, or at arr.length + fromIndex for negative values of fromIndex (using the absolute value of fromIndex as the number of characters from the end of the array at which to start the search).


Another "old school" way of doing it could be this: declare an object (o) and add sub-arrays to it with a key generated from the contents of each array. This object will then keep its unique structure by itself:

var o={d:{},add:function(nom,code){this.d[nom+code]=[nom,code]},
get:function(){return Object.values(this.d)}};

You add values to it with

o.add(el.nom, el.codePosteaux[0]);

and retrieve the unique array from it with

o.get()

How to check if array includes a value in JavaScript?, Checking for Array of Objects using some(). For a more versatile solution that works on other data types, you may want to use some instead. ".some  The Array.filter () method creates a new array with only elements that pass a test you include as a callback function. We can use it to remove the duplicates. On each iteration, we’ll use Array.indexOf () to see if our item already exists. If the returned index is smaller than the current index, that means an instance of item already exists.


Javascript return duplicates from array, Yes there is an issue with jQuery. Here we use another built-in method of JavaScript arrays, indexOf() that returns the first index where it found our provided element in Types of primitive values include Boolean, Null, Undefined​, Number, String and Symbol. FeaturesInside the inner loop check for duplicate element. The methods arr.indexOf, arr.lastIndexOf and arr.includes have the same syntax and do essentially the same as their string counterparts, but operate on items instead of characters: arr.indexOf(item, from) – looks for item starting from index from, and returns the index where it was found, otherwise -1.


How to get all unique values (remove duplicates) in a JavaScript , Given an array which contains some values, the task is to remove the duplicate exist in the output array with unique values, then add the element to the output array. Method 2: Using array filter() method: The arr.filter() function is used to create a new How to check all values of an array are equal or not in JavaScript ? Problem : Given an array of positive integers find all the duplicate elements. Algorithm : Iterate over the array using forEach Find if there is a duplicate for the element using indexOf indexOf takes two arguments first the element and the second one is the starting index We provide the starting index as the index + 1 where index is the index of the current element We will find if the same


Remove duplicate objects from array javascript lodash, We are using ES6 map and filter methods to remove the duplicate objects from an Having covered the two steps common to every solution to this problem, we shall new array with only elements that pass a test you include as a callback function. As PM 77-1 suggests, consider using the built–in Array. filter() method​. js  Thanks to Kristian Sletten for pointing out the issue with the loop skipping the following item. Using the Array filter Method to Remove Items By Value. Unlike the splice method, filter creates a new array. filter() does not mutate the array on which it is called, but returns a new array. filter() has a single parameter, a callback method.