Spark
Spark

Reputation: 1037

function always returning false

Fairly new to Javascript, could anybody tell me why this simple array loop / string comparison function always returns false? They're both of type string and the data is the same, the loop should absolutely return true. Possible syntax error? Also is there an easier way of running this check.

function imageDuplicate(fileName)
{
    $.each(previewImagesArray, function(index)
    {
        if(previewImagesArray[index].name == fileName)
            return true;
    });
    return false
}

Thanks in advance.

Upvotes: 0

Views: 2695

Answers (5)

Dalorzo
Dalorzo

Reputation: 20014

How about this instead:

function imageDuplicate(fileName)
{
   return  previewImagesArray.some(function(item)
    {
        return item.name === fileName;
    });
}

Important: this will work on IE9+ if you need this to run in older version of IE please follow the polyfill instructions here.

Other post samples:

javascript find an object with specific properties in an array

Upvotes: 8

jansepke
jansepke

Reputation: 1979

one tweak would be to use the value directly

    $.each(previewImagesArray, function (index, value) {
        if (value.name == fileName) {
            ...
        }
    });

Upvotes: 0

ssilas777
ssilas777

Reputation: 9804

As mentioned in the comment returning from each loop, doesn't return from function.

Try something like this

function imageDuplicate(fileName)
{
    var isDuplicate = false;
    $.each(previewImagesArray, function(index)
    {
        if(previewImagesArray[index].name == fileName){
            isDuplicate = true;
            return false; //exit from each loop
       }
    });
    return isDuplicate; 
}

Upvotes: 0

David P. Caldwell
David P. Caldwell

Reputation: 3821

The code inside function(index) is a separate function, nested inside imageDuplicate. The return value of that function would be processed by .each() as it sees fit.

As such, the only statement which returns from your outer function is your return false.

As other answers are illustrating in code, you can declare a variable in the scope of imageDuplicate and have the inner function access and modify that value in order to get the effect you're wanting.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You are returning true from the the anonymous inner function, not from imageDuplicate, instead use a flag variable as shown below

function imageDuplicate(fileName) {
    var valid = false;
    $.each(previewImagesArray, function (index) {
        if (previewImagesArray[index].name == fileName) {
            valid = true;
            //to stop the iteration
            return false
        }
    });
    return valid
}

Upvotes: 12

Related Questions