3

There is a way to lower the sensibility of the indexOf? Like this

var arr = ["Hello", "stackoverflow"]
var idx = arr.indexOf("stack")

And get idx = 1 instead of idx = -1

urco
  • 189
  • 1
  • 5
  • 16

2 Answers2

4

You'd have to write your own function for that. Something like this would work:

function searchArr(arr, str) {
    for (var i=0;i<arr.length;i++) {
        if (arr[i].indexOf(str) !== -1) return i;
    }
    return -1;
}
searchArr(arr, 'stack');// returns 1

That simply iterates through the array you enter as the first argument, and keeps going until it finds an index where the array's value at that index contains the search string.

Joeytje50
  • 18,636
  • 15
  • 63
  • 95
1

The following will return an array of true and false showing which array elements match "stack".

var arr = ["Hello", "stackoverflow"];
var idx =arr.map(function(s) {return s.indexOf("stack") !== -1});

If simply want to check if a match exists, you could use

var arr = ["Hello", "stackoverflow"];
var matchFound =arr.some(function(s) {return s.indexOf("stack") !== -1});
Dag Sondre Hansen
  • 2,449
  • 20
  • 22
  • Worth noting that this [doesn't work in IE8](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Browser_compatibility). – Joeytje50 May 17 '14 at 18:57
  • Such an array is not exactly what the OP wanted, is it? – Bergi May 17 '14 at 18:59
  • Unclear what he wants - the sample code seems to want both an array index and a position index. – Dag Sondre Hansen May 17 '14 at 19:01
  • 1
    For a check whether it exists, you should use `some` not `filter`. – Bergi May 17 '14 at 19:01
  • @Joeytje50 in my opinion best practice is to use polyfill to compensate for this - polyfills can usually be found at MDN (your link is a good example). Seems the only logical way to benefit from new, native additions to Javascript. – Dag Sondre Hansen May 19 '14 at 06:35