2

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?

1
  • 3
    use Set Commented Jul 6, 2020 at 6:38

4 Answers 4

3

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"))
});
...
Sign up to request clarification or add additional context in comments.

Comments

0

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);
   }

Comments

0

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];

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.