How to search for a string inside an array of strings

JavascriptArraysSearch

Javascript Problem Overview


After searching for an answer in other posts, I felt I have to ask this. I looked at <https://stackoverflow.com/questions/237104/javascript-array-containsobj> and <https://stackoverflow.com/questions/143847/best-way-to-find-an-item-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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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;
}

Solution 4 - Javascript

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)

Solution 5 - Javascript

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" } ]

Solution 6 - Javascript

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>

Solution 7 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsomeuserView Question on Stackoverflow
Solution 1 - JavascriptAleadamView Answer on Stackoverflow
Solution 2 - JavascriptChetan KhilosiyaView Answer on Stackoverflow
Solution 3 - JavascriptJanick BernetView Answer on Stackoverflow
Solution 4 - JavascriptAlex WView Answer on Stackoverflow
Solution 5 - JavascriptKashan HaiderView Answer on Stackoverflow
Solution 6 - JavascriptRavi AsharaView Answer on Stackoverflow
Solution 7 - JavascriptMohamed IsmailView Answer on Stackoverflow