View Full Version : finding a substring in an array?

10-08-2012, 11:59 PM
ok so i have it so that ill type a command in like /ban @name and itll
take everything after @ and put it into a variable (substring method).

i also have a users list which takes down everyones user name and user id in the chat room im in and puts it into an array in the format name=userid

so lets say someone is represented in the userlist array as
johnson = 1000000000

if i try to use array.indexOf(substring) it returns -1 every time....

even if substring = johnson

so long story short my question is how would i compare my substring to the users list and have it find their name which is attached to their user id and give me the index location of their name, strip the user id out of it and put it into a different array.

Old Pedant
10-09-2012, 12:58 AM
The problem is that Array.indexOf and String.indexOf are very very different.

String.indexOf indeed looks for a substring in the string.
But Array.indexOf looks for an array *ELEMENT* (the ENTIRE element) that matches the given test value.

So the quick answer to your question is: Write code!

function findSubstringInArray( ary, str )
for ( var a = 0; a < ary.length; ++a )
if ( ary[a].indexOf(str) >= 0 ) { return a; } /* return element number of found match */
return -1; /* not found */

Now... If this is something you do all the time, you might want to extend the Array prototype to add a method that will do as you wish. But if it's something you only do in one place in one page, just use simple code as shown.

Old Pedant
10-09-2012, 01:01 AM
I don't understand this part of your post:

give me the index location of their name, strip the user id out of it and put it into a different array.
I did the "give me the index location".

But I don't understand the point of putting the result(s) in a different array.

Presumably, there will only be one result, so why does it need to go into an array??

And even if you modified my code to find multiple results, after stripping out the userids all that is left are the numeric values, so the new array would end up looking like

[ 1000000, 1887331, 2000181 ]

How would that be useful?

Old Pedant
10-09-2012, 01:06 AM
I also have to ask: Suppose your incoming array looks like this:

[ "adamson = 123", "jones = 775", "adams = 999" ]

If you ask for "adams", you are going to find "admason" first. Is that really what you want?

Seems to me like this kind of array is a mistake. I think you would want an object with multiple properties, thus:

var userinfo = {
"adamson" : 123,
"jones" : 775,
"adams" : 999

And now you could just do

var value = userinfo["adams"];

Much more efficient and you won't get "false positive" matches.