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?
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);
Extending the contains function you linked to:
containsRegex(a, regex){
for(var i = 0; i < a.length; i++) {
if(a[i].search(regex) > -1){
return i;
}
}
return -1;
}
Then you call the function with an array of strings and a regex, in your case to look for height:
containsRegex([ '<param name=\"bgcolor\" value=\"#FFFFFF\" />', 'sdafkdf' ], /height/)
You could additionally also return the index where height was found:
containsRegex(a, regex){
for(var i = 0; i < a.length; i++) {
int pos = a[i].search(regex);
if(pos > -1){
return [i, pos];
}
}
return null;
}
It's faster to avoid using regular expressions, if you're just trying to find the first substring match within an array of string values. You can add your own array searching function:
Code:
Array.prototype.findFirstSubstring = function(s) {
for(var i = 0; i < this.length;i++)
{
if(this[i].indexOf(s) !== -1)
return i;
}
return -1;
};
Usage:
i.findFirstSubstring('height');
Returns:
-1 if not found or the array index of the first substring occurrence if it is found (in your case would be 2
)
Simple and Great Code, Support Multi words
let strArray = ["Please locate where 'locate' occurs!","Hi Hashem it","do it","for free"];
strArray.filter(word=> word.includes("it"));
Output
//Hi Hashem it,do it
//-------------------
strArray.filter(word=> word.includes("do it"));
Output
//do it
In-case if someone wants a little dynamic search.
let searchInArray=(searchQuery, array, objectKey=null)=>{
return array.filter(d=>{
let data =objectKey? d[objectKey] : d //Incase If It's Array Of Objects.
let dataWords= typeof data=="string" && data?.split(" ")?.map(b=>b&&b.toLowerCase().trim()).filter(b=>b)
let searchWords = typeof searchQuery=="string"&&searchQuery?.split(" ").map(b=>b&&b.toLowerCase().trim()).filter(b=>b)
let matchingWords = searchWords.filter(word=>dataWords.includes(word))
return matchingWords.length
})
}
For an Array of strings:
let arrayOfStr = [
"Search for words",
"inside an array",
"dynamic searching",
"match rate 90%"
]
searchInArray("dynamic search", arrayOfStr)
//Results: [ "Search for words", "dynamic searching" ]
For an Array of Objects:
let arrayOfObject = [
{
"address": "Karachi Pakistan"
},
{
"address": "UK London"
},
{
"address": "Pakistan Lahore"
}
]
searchInArray("Pakistan", arrayOfObject,"address")
//Results: [ { "address": "Karachi Pakistan" }, { "address": "Pakistan Lahore" } ]
var newArr= [];
function searchStringInArray (str, strArray) {
newArr = [];
strArray.map(item => {
str.includes(item) ? newArr.push(item) : '';
});
return newArr;
}
var result = searchStringInArray('Definitely",he said in a matter-of-fact tone.', ['matter', 'definitely']);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
To search inside an array you can simply use an Iteration method ( forEach/ map ) and, inside that use JavaScript String search method
Reference https://www.w3schools.com/jsref/jsref_search.asp
Example
const arrayOfLists = ['ape', 'apple', 'auto'];
const searchString = "A"
let matchingStrings = [];
arrayOfLists.forEach((list) => {
if (list.toLocaleLowerCase().search(searchString.toLocaleLowerCase()) > -1) {
matchingStrings.push(list)
}
})
matchingStrings array will have list of all likely occurrences
精彩评论