3

I have an array of values with names:

names = ['Jim', 'Jack', 'Fred']

I have also received a value from a function, which is a name in string form, such as:

returnedValue = 'Jim'

How can I run the returnedValue string against the values of the names array and test for a match?

My feeling is that you would want to use the .filter method of the array prototype but I can't conceive of how to do it that way.

Anthony
  • 13,434
  • 14
  • 60
  • 80

3 Answers3

11

There is an indexOf method that all arrays have (except in old version of Internet Explorer) that will return the index of an element in the array, or -1 if it's not in the array:

if (yourArray.indexOf("someString") > -1) {
    //In the array!
} else {
    //Not in the array
}

If you need to support old IE browsers, you can use polyfill this method using the code in the MDN article.

Copied from https://stackoverflow.com/a/12623295/2934820

Community
  • 1
  • 1
Sharon
  • 757
  • 6
  • 21
  • 44
0

the Array.indexOf method will return a value with the position of the returned value, in this case 0, if the value is not in array you'd get back -1 so typically if you wanna know if the returnedValue is in the array you'd do this if (names.indexOf(returnedValue) > -1) return true; Or you can do ~~ like Mr. Joseph Silber kindly explains in another thread

Shiala
  • 486
  • 3
  • 8
-1

Check out this link on dictionaries https://www.w3schools.com/python/python_dictionaries.asp If you have a variable whose value would match a string in the dictionary you can set a variable to equal that value. Here is a snip from some of my own code`

global element1
element1 = 1
elementdict = {
"H": 1.008,
"He": 4.00,
"Li": 6.49,
"Be": 9.01,
"B": 10.81,
"C": 12.01,
"N": 14.01,
"O": 16.00,
"F": 19.00,
"Ne": 20.18,
"Na": 22.99,
"Mg": 24.30
}
element1 = input("Enter an element to recieve its mass")
element1 = elementdict[element1]
print(element1)
Bobby
  • 1
  • 4
    Welcome to SO! You might want to review [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). The answer you provided is for Python and the question was about JavaScript. – displacedtexan Feb 19 '20 at 21:04