54

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?

Community
  • 1
  • 1
someuser
  • 543
  • 1
  • 4
  • 4

8 Answers8

62

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.

Saurabh Kumar
  • 5,576
  • 4
  • 21
  • 30
Aleadam
  • 40,203
  • 9
  • 86
  • 108
  • many thanks. seems like my JS code isn't working though. [here](http://corp.flixuniverse.com/bctest/txtappend.html) i'm trying to use this search function, in order to append new text to the array element after which corresponds with the search. the html code used for the array is [here](http://corp.flixuniverse.com/bctest/query.txt). nothing happens when click the button, and the problem is with var 't' somehow. if u comment lines 19,20 at least the button will output the code. but from some reason it doesn't work when u try to call the search function. many thanks once again. – someuser Mar 24 '11 at 21:03
  • There's a typo in the if statement (missing the parentheses). I'll fix it asap. BTW, if you're developing with firefox, make sure you install firebug. Or use "inspect element" in Chrome. That's how I found the bug fast. Firebug console: `missing ( before condition [Break On This Error] if stringArray[j].match ("height") return j;` – Aleadam Mar 24 '11 at 21:14
  • yep, thanks. actually I have firebug installed but I somehow forgot to enable it. looking forward for the fix and thanks again. – someuser Mar 24 '11 at 21:20
  • This should be called "searchStringArray" because the search can be performed with a regex not just a string – Steven Lu Mar 09 '14 at 05:33
  • This will only find the first element of the array that is a match, not all elements that match. – Buttle Butkus May 05 '15 at 23:12
  • I keep getting "TypeError: strArray[i].match is not a function" with this solution. – Christoffer May 14 '15 at 12:57
  • 2
    Because array.indexOf() and array.find() didn't exist when most of this thread took place. – Roger Krueger Dec 11 '16 at 04:53
23

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);
Chetan Khilosiya
  • 491
  • 5
  • 16
12

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;
}
Janick Bernet
  • 20,544
  • 2
  • 29
  • 55
5

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)

Community
  • 1
  • 1
Alex W
  • 37,233
  • 13
  • 109
  • 109
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
0

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" } ]
Kashan Haider
  • 1,036
  • 1
  • 13
  • 23
0

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>
Ravi Ashara
  • 1,177
  • 7
  • 16
0

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

Mohamed Ismail
  • 367
  • 1
  • 7