vsl0610
vsl0610

Reputation: 59

Finding a specific string in array of strings

In an array of strings, a loop returns false if it finds that one of the strings is not what we are looking for.

If it doesn't find an unmatching string, the array is correct and it should return true. It keeps returning false even when the array has no "mistakes"

I have tried using indexOf, for loop and while loops, all of them unsuccessful.

function brackets() {
    var testArr = ['()', '{}', '()']

    /* Method 1 --- returns false even when the parenthesis are ok, I guess
    it's because the indexOf only searches for the first element that matches 
    the criteria */

    if (testArr.indexOf("()") == -1 || testArr.indexOf("{}") == -1 ||
        testArr.indexOf("[]") == -1) {
        return false
    } else {
        return true
    }

    /* Method 2 --- for loop. Same story, returns false, even when all   
    testArr[i] === any of the cases and none of them is !==, it behaves as if it was 
    false. I'm not sure why */

    for (i = 0; i < testArr.length; i++) {
        if (testArr[i] !== "()" || testArr[i] !== "{}" || testArr[i] !== "[]") {
            return false
        }
    }
    return true
}

brackets()

Upvotes: 2

Views: 86

Answers (4)

brroshan
brroshan

Reputation: 1650

This should do it:

var testArr = ['()', '{}', '()'];

if(testArr.some(function(e){ return /(){}/g.test(e) })){
   console.log("found");
} else {
   console.log("not found");   
}

Finding all instances of "()" and "{}"

https://jsfiddle.net/dhoh1932/1/

Upvotes: 0

Luca Colonnello
Luca Colonnello

Reputation: 1456

In the second method you can use an AND operator to solve this problem.

function brackets() {
var testArr = ['()', '{}', '()'];

/* Method 2 --- for loop. Same story, returns false, even when all   
testArr[i] === any of the cases and none of them is !==, it behaves as if it was 
false. I'm not sure why */

for (i = 0; i < testArr.length; i++) {
    if (testArr[i] !== "()" && testArr[i] !== "{}"  && testArr[i] !== "[]") {
        return false;
    }
}
return true;
}

brackets();

Upvotes: 4

Mistergreen
Mistergreen

Reputation: 1052

You've created an array with

var testArr = ['()', '{}', '()']

so if you need to test the string you need to test the 2-d array

if (testArr[0].indexOf("()") == -1

Upvotes: 0

victor175
victor175

Reputation: 624

Change your array to : var testArr = ['()', '{}', '[]']

Since you do

 if (testArr.indexOf("()") == -1 || testArr.indexOf("{}") == -1 ||
        testArr.indexOf("[]") == -1)

Then even if one of these parenthesis is absent from the array, the condition will return false.

Upvotes: 0

Related Questions