Block duplicates when adding to an array in JavaScript

Viewed 71

I am beginner in JavaScript. I have this code:

var imageArray = [];

$(document).on("click", ".showPrv", function () {
    $("#dropzone").each(function () {
        $(".dz-image-preview").each(function () {
            $(".dz-image").each(function () {
                imageArray.push($(this).find("img").attr("src"))
            });
        });
    });
    console.log(imageArray);
})

This code works fine, but I have a problem with duplicates in my array imageArray. How can you block duplicates from being added to this table?

4 Answers

Try to use the includes() function.

Using it will be:

...
$(".dz-image").each(function () {
    if(!imageArray.includes($(this).find("img").attr("src")))
        imageArray.push($(this).find("img").attr("src"))
});
...

You can check if the value exists in the imageArray before pushing a new one, somewhat like this:

   const imgSrc = $(this).find("img").attr("src");
   if(!imageArray.includes(imgSrc)) {
       imageArray.push(imgSrc);
   }

I would recommend using a Set for this, as it allows for a quick lookups (O(1)) in order to check if the value already exists. Using an array forces you to do .includes() which takes O(n) time.

const imageSet = new Set();
...
const imgSrcAttr = $(this).find("img").attr("src");
if(!imageSet.has(imgSrcAttr)) {
   imageSet.add(imgSrcAttr);
}
...

If at some point you need to convert the set to an array, you can simply use the spread-operator:

const imageArr = [...imageSet];

If the element was not found, -1 will be returned. Refer to $.inArray():

// If not in your array then
if($.inArray($(this).find("img").attr("src"), imageArray) === -1){

     // Add value to imageArray
     imageArray.push($(this).find("img").attr("src"));
}

Example of $.inArray() on JSFiddle for better understanding.

Related