Dean Arvin
Dean Arvin

Reputation: 115

Filter EVERY string in an array that contains a specific value

I've got an array:

var stringOne = ["big dog","small dog", "big cat", "small cat"]

And I want to filter out every string that contains "dog".

Of course the function of:

var stringTwo = stringOne.filter((e) => e !== "dog")

doesn't work as there is no string of exactly "dog", but I'm curious if there's a built in function to accomplish this?

Upvotes: 0

Views: 62

Answers (3)

نور
نور

Reputation: 1527

source link

source link

function myFunction(reg) {
    var stringOne = ["big dog","small Dog", "big cat", "small cat"];
  var dogs = stringOne.filter(function(val){
      if(val.toLowerCase().match(reg)){
        return val;
    }
  });
  console.log(dogs)
}
var reg = /dog/g;
 myFunction(reg);

Upvotes: 0

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

You can achieve this by using String.prototype.includes:

var stringOne = ["big dog", "small dog", "big cat", "small cat"]

const filterByWord = (arr, word = "") => {
  return arr.filter(s => {
    return s.toLocaleLowerCase().includes(word.toLocaleLowerCase());
  });
}
console.log(filterByWord(stringOne, "dog"));

Upvotes: 5

Aaron
Aaron

Reputation: 14029

String#includes is the simplest way but it is limited to the exact string you're searching for. I.e.:

"small dog".includes("dog") #=> true
"Big Dog".includes("dog")  #=> false

Typically software developers will lowercase strings (String#toLowerCase) before doing comparisons to normalize them.

"Big Dog".toLowerCase().includes("dog")  #=> true

Another incredibly useful but also complicated tool you should be aware of are regular expressions (regex or regexp for short). These allow you to use a special syntax to determine if a given string matches the conditions you've specified. I think a regexp is overkill for this use case but they have features that sidestep the casing problem.

regexp = /dog/i #=> match the case insensitive sequence of letters "dog"
regexp.test("small dog") #=> true
regexp.test("Big Dog")   #=> true

Upvotes: 3

Related Questions