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.

5
  • 2
    Use indexOf Commented Dec 3, 2014 at 4:24
  • 1
    names.indexOf(returnedValue) Commented Dec 3, 2014 at 4:24
  • possible duplicate of JavaScript find array index with value Commented Dec 3, 2014 at 4:32
  • filter() would be used to count or find all the matches instead of just the first (or last via lastIndexOf()) Commented Dec 3, 2014 at 4:32
  • names.contains works in es6 Commented Jan 28, 2015 at 17:56

3 Answers 3

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

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

1 Comment

I was looking allll over the internet for this. THANK YOU!
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

Comments

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

1 Comment

Welcome to SO! You might want to review How do I write a good answer?. The answer you provided is for Python and the question was about JavaScript.

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.