[javascript] How to search for a string inside an array of strings

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?

This question is related to javascript arrays search

The answer is


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)


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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array? Find a file by name in Visual Studio Code Search all the occurrences of a string in the entire project in Android Studio Java List.contains(Object with field value equal to x) Trigger an action after selection select2 How can I search for a commit message on GitHub? SQL search multiple values in same field Find a string by searching all tables in SQL Server Management Studio 2008 Search File And Find Exact Match And Print Line? Java - Search for files in a directory How to put a delay on AngularJS instant search?