0

I have an array of strings stringsArr and also I have a string myString. I would like to find first index of my array for which value is euqal myString OR contains myString.

I know method indexOf(), but unfortunatelly it works only if value equals myString. I googled through documentation, but didn't find anything suitable, so decided to ask here if I didn't miss something.

0

2 Answers 2

4

You want to use findIndex and a custom predicate like:

stringsArr.findIndex(function (str) {
  return (str === myString || str.indexOf(myString) > -1);
});

If you're using an environment(/browser) that doesn't provide findIndex, the MDN page includes a nice short polyfill.

Sign up to request clarification or add additional context in comments.

4 Comments

You've forgot to mention - es2015.
Nice solution, but still does not work for too many browsers :) Next project will write with babel, so will use it for sure
@Kania check the MDN page for a polyfill. You can add findIndex to all the current browsers and use it today.
Unfortunately in existing code adding polyfills is not an option :D looking forward for new project! Thanks for showing this solution!
1

indexOf is probably what you want, but using indexOf on the String:

var tested = ['foot','bark', 'foo','cat'];
var match = 'foo';
for(var i = 0; i < tested.length; i++)
    if(tested[i].indexOf(match) > -1) console.log(i);

That will output 0 and 2.

To get the actual index:

var tested = ['foot','bark', 'foo','cat'];
var match = 'foo';
var index = -1;
for(var i = 0; i < tested.length; i++) {
    if(tested[i].indexOf(match) > -1) {
       index = i;
       break;
    }
} 

console.log(index); // 0, as "foot" includes "foo".

2 Comments

I'm looking for 'foobar' and 'foo', but indexOf returns ONLY 'foo'
nice, thank you, but my own solution I already have, question was about existing in JavaScript solution, like mentioned findIndex().

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.