Specific vaule in varibles? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Specific vaule in varibles?

I want to have an if statment that is able to run if a vaule has one particular vaule in a way that can be used for many different vaules E.g.. Var people= ["Josh", "Philip", "Karan"] If (people === "Philip) { } Note I need it to not have an array number so that code can run efficiently (so if people[1] === Philip is not a good answer)

30th Aug 2020, 5:18 AM
Cam UOR
Cam UOR - avatar
5 Answers
+ 3
If i got you right, you want to know if a particular string exist in an array? check this out https://code.sololearn.com/Wc8w3zNBjBem/?ref=app
30th Aug 2020, 10:07 AM
Ibrahim Yusuf
Ibrahim Yusuf - avatar
+ 5
Array has an includes() method, it will return a boolean(true/false) depending on whether the value in question is present in the array. If (people.includes("Philip")) { } JavaScript Array includes() Method - https://www.w3schools.com/jsref/jsref_includes_array.asp JavaScript Array Methods - https://www.w3schools.com/js/js_array_methods.asp JavaScript Array Reference - https://www.w3schools.com/jsref/jsref_obj_array.asp
30th Aug 2020, 3:47 PM
ODLNT
ODLNT - avatar
+ 4
var people = ["Josh","Philip ","Karan "]; if(people.indexOf("Philip") != -1){ console.log("found"); }else{ console.log("not found"); } if what you want is to check if the value exists in array you can use IndexOf() it returns the index of element if found or -1 if not found.
30th Aug 2020, 6:42 AM
Bahhaⵣ
Bahhaⵣ - avatar
+ 4
Adding to Bahha🐧's example, you can write a function which returns true and false depending on if value is there or not. function isValueInArray(arr, value) { return arr.indexOf(value) >= 0; } Notice how you have to pass both array and value to the function? Using prototypes we can solve that problem. Learn about prototypes: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes https://code.sololearn.com/WLqeZp3H9gHi/?ref=app
30th Aug 2020, 11:37 AM
Raj Chhatrala
Raj Chhatrala - avatar
0
Thank you everyone!
31st Aug 2020, 2:12 AM
Cam UOR
Cam UOR - avatar