S.P.
S.P.

Reputation: 369

String comparing in for loop

I want to check if string is same from an array object or not before sending to a table form, but it can be the same if you didn't change anything in the edit zone. User fill down the table form and send it to the server, next time if user edit the form I want to check if the value are same as the array (which store the previous informations from the table), but it's ok if user didn't change anything but enter to the edit zone. The problem is my code checked that there's no same string but it popup either the true or the false alert message, it popup every message while checking the table form and go into the "false" statement, so I can send nothing after checking string. I will appreciate any help, thx! :)

var arr = [{words: a},{words: b},{words: c},{words: d}];
var val = $('#somethingFromHTML').val()
    for(var i = 0; i < arr.length; i++) {
        if (arr[i].words.indexOf(val) > -1){
            alert("duplicate words")
            return false
        } else if (arr[i].words.indexOf(val) === -1 || arr[i].words === val){
            alert("there's no duplicate words")
            return true
        }
    }

Upvotes: 0

Views: 72

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074365

You code always returns the result of checking only arr[0].words, it never moves on to arr[1].words at all, because

  • You have a return in both of your if blocks, and

  • Your second if condition is, in part, the inverse of the first one

Consequently, if val is in arr[0].words (indexOf returns > -1), the code will return false. Otherwise, it will return true, because by definition, indexOf returned -1 and your second condition is "if it's -1 or ...". The second part of the or is irrelevant, because the first part will be true.

The minimal change is to put the return true after the loop:

var arr = [{words: a},{words: b},{words: c},{words: d}];
var val = $('#somethingFromHTML').val();
for(var i = 0; i < arr.length; i++) {
    if (arr[i].words.indexOf(val) > -1){
        alert("duplicate words");
        return false;
    }
}
alert("there's no duplicate words");
return true;

...but arrays have a feature for just this situation: Array.prototype.some:

var arr = [{words: a},{words: b},{words: c},{words: d}];
var val = $('#somethingFromHTML').val();
if (arr.some(function(entry) { entry.words.indexOf(val) > -1})) {
    alert("duplicate words");
    return false;
} else {
    alert("there's no duplicate words");
    return true;
}

some calls its callback repeatedly with the entries in the array, in order, until the callback returns a truthy value. If the callback ever does that, some returns true; if it reaches the end of the array with the callback never having returned a truthy value, it returns false. So it's useful for checking if any entry in the array matches a condition.

Upvotes: 1

Related Questions