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!

1
  • STRING.indexOf(needle) in a loop ? Commented May 4, 2016 at 8:49

3 Answers 3

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);

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

4 Comments

I do not fully grasp the need for the complexity of your code. Why be case insensitive on a number and why the bind?
The some is really good. Yes, why case insensitive on a number?
@PraveenKumar, it was for future reference ... ;)
@mplungjan, try it without bind, it does not work outside of a function around.
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

2 Comments

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").
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.
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));
});

Comments

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.