2

I have searched across the web though have not had any luck in correcting my issue. What I want to do is search an array for a substring and return the result. An example of the array is like this:

the_array = ["PP: com.package.id, NN: Package Name","PP: com.another.id, NN: Another Name"];

What I want to do is search the_array for com.package.id making sure that it appears between the "PP:" and ",". Also please note that the array will contain several thousand values. Hope you can help, thank you.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
ctrled
  • 23
  • 2
  • 1
    What did you try? All you can do is iterating over the array and examine each string. – Felix Kling Jul 30 '11 at 22:36
  • possible duplicate of [In javascript, how do you search an array for a substring match](http://stackoverflow.com/questions/4556099/in-javascript-how-do-you-search-an-array-for-a-substring-match) – ripper234 Sep 14 '11 at 09:59

1 Answers1

2

Easy way:

the_array.join("|").indexOf([str]) >= 0;

Other ways would be to loop thru the array using .each() or a simple for loop

Array.prototype.each = function(callback){
    for (var i =  0; i < this.length; i++){
        callback(this[i]);
    }
}

the_array.each(function(elem){
    console.log(elem.indexOf('<searchString goes here>'));
});
Mrchief
  • 75,126
  • 20
  • 142
  • 189
  • `each` is not a JavaScript function. – Felix Kling Jul 30 '11 at 22:37
  • 1
    FWIW, ECMAScript 5 introduced `forEach`: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/foreach You can also find an alternative implementation there. But it seems to me that `each` is irrelevant for the problem. – Felix Kling Jul 30 '11 at 22:46
  • Yes and Yes. Since ES5 is not universally supported yet, we need these workarounds. – Mrchief Jul 30 '11 at 22:48
  • @Mrchief it is 'each.indexOf'. Please change it. – Kamal Reddy Jul 23 '13 at 12:12
  • @KamalReddy: It's pseudocode, note that `[str]` is not an array but placeholder for search string in question. But I'll edit for clarity anyway. – Mrchief Jul 24 '13 at 03:07