yoursurrogategod Posted August 3, 2012 Share Posted August 3, 2012 Hi all, I recently found this link in order to find the first occurrence of a value in a JavaScript array. http://api.jquery.com/jQuery.inArray/ However, what if I want to find every occurrence of the value "Bob" in an array that has multiple Bobs? After spending some time on Bing, I couldn't find the answer. Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 3, 2012 Share Posted August 3, 2012 Hmm . . . look at the page that you linked to jQuery.inArray( value, array [, fromIndex] ) value: The value to search for. array: An array through which to search. fromIndex: The index of the array at which to begin the search. The default is 0, which will search the whole array. Look at that last, optional parameter. That tells the function what index you want the searching to start from. The function returns the index of the first found match, right? So, just create a loop to continue looking for a match and increasing the index after each match. var indexMatches = newArray(); var index = 0; while(jQuery.inArray(haystackArr, needle, index) != -1) { index = jQuery.inArray(haystackArr, needle, index); indexMatches[indexMatches.length] = jQuery.inArray(haystackArr, needle, index); } Not tested Quote Link to comment Share on other sites More sharing options...
yoursurrogategod Posted August 3, 2012 Author Share Posted August 3, 2012 I thought about that before. I was hoping that there would be a way to have one function call (I'm not very familiary with JS or jQuery, so don't know everything about them) that returns an array of integers that I can just use. I know that you can encapsulate that functionality in a method, but didn't know if there was a native function that does this. Thanks for your help again. Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 4, 2012 Share Posted August 4, 2012 I thought about that before. I was hoping that there would be a way to have one function call (I'm not very familiary with JS or jQuery, so don't know everything about them) that returns an array of integers that I can just use. I know that you can encapsulate that functionality in a method, but didn't know if there was a native function that does this. I'm not too familiar with JQuery. There might be a function to do that, but I'm guessing not. Just wrap the code above in a function and use that. function (haystackArr, needle) { var indexMatches = newArray(); var index = 0; while(jQuery.inArray(haystackArr, needle, index) != -1) { index = jQuery.inArray(haystackArr, needle, index); indexMatches[indexMatches.length] = jQuery.inArray(haystackArr, needle, index); } return indexMatches; } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.