After searching for an answer in other posts, I felt I have to ask this. I looked at How do I check if an array includes an object in JavaScript? and Best way to find if an item is in a JavaScript array? and couldn't get the code there to work.
I am capturing an html embed code into an array, so each item is a line of html code.
for example:
i[0]='<param name=\"bgcolor\" value=\"#FFFFFF\" />' i[1]='<param name=\"width" value=\"640\" />' i[2]='<param name=\"height\" value=\"360\" />' i[3]='more html code'
I want to search this array and find the line where the word 'height' is.
So ideally, I'd like to write a function that returns the index of the item where 'height' appears.
Fortunately, there are no duplicates in this array, so there's only one occurrence.
with simple object search I get 'false' returns.
Any idea?
Use Linq Contains() method to search for as specific string in an array of strings. string[] arr = { "Bag", "Pen", "Pencil"}; Now, add the string in a string variable i.e. the string you want to search.
Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.
It's as simple as iterating the array and looking for the regexp
function searchStringInArray (str, strArray) { for (var j=0; j<strArray.length; j++) { if (strArray[j].match(str)) return j; } return -1; }
Edit - make str
as an argument to function.
You can use Array.prototype.find function in javascript. Array find MDN.
So to find string in array of string, the code becomes very simple. Plus as browser implementation, it will provide good performance.
Ex.
var strs = ['abc', 'def', 'ghi', 'jkl', 'mno']; var value = 'abc'; strs.find( function(str) { return str == value; } );
or using lambda expression it will become much shorter
var strs = ['abc', 'def', 'ghi', 'jkl', 'mno']; var value = 'abc'; strs.find((str) => str === value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With