0

I'm having a problem in searching in an array. I wanted to check if a certain string exists in one of the elements, example

Array:

["4_1", "4_2", "4_3"]

I will check if the string "4" exists in one of the variables.

Thank you!

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
mengmeng
  • 1,266
  • 2
  • 22
  • 46

3 Answers3

3

You could use a loop for it.

var arr = ["4_1", "4_2", "4_3"];
    search = RegExp(4),
    result = arr.some(search.test.bind(search));

document.write(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

The Easiest way is to use Array.prototype.join && indexOf methods

["4_1", "4_2", "4_3"].join("").indexOf("4")

Update

According to @t.niese's comment this answer may cause wrong result, for example if you are looking for 14 it will return 2 - what is wrong because your array doesnt contain element which begins on 14. In this case better to use @Nina's answer or you can join it in another way ["4_1", "4_2", "4_3"].join(" ").indexOf("14") // -1

The Reason
  • 7,705
  • 4
  • 24
  • 42
  • The performance might not be the best for larger arrays, and will also have a problem, if the OP decides to use a string with more then on char as `needle` , because it will then give a false positive for `["4_1", "4_2", "4_3"].join("").indexOf("14")`. – t.niese May 04 '16 at 08:57
  • For all `.join` it will be possible to find a failure case: `["4_1", "4_2", "4_3"].join(separator).indexOf("1"+separator+"4")` will show a result. If the OP really only looks for numbers, then it will work. But because the question itself is only a generic `[...]I wanted to check if a certain string exists in one of the elements[...]` then under this conditions a `.join` will never be a good solution. – t.niese May 05 '16 at 08:35
0

You can actually make a loop and check the indexOf to be not -1:

["4_1", "4_2", "4_3"].forEach(function (element, index, array) {
  if (element.indexOf(4) != -1)
    alert("Found in the element #" + index + ", at position " + element.indexOf(4));
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252