Filter array by content?

2020-01-19 06:38发布

问题:

I'm trying to filter an array that is non-object based, and I need the filter to simply check each piece of the array for a specific string.

Say I have this array:

["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"]

What I need to do is harvest the array in a way so that I get a new array that only contain those who start with http://mywebsite.com and not http://yourwebsite.com

In conclusion making this: ["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"]

into this ["http://mywebsite.com/search", "http://mywebsite.com/search"]

回答1:

You can filter the array using .filter() and .startsWith() method of String.

As from Docs:

The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.

Demo:

let data = ["http://mywebsite.com/search",
            "http://mywebsite.com/search",
            "http://yourwebsite.com/search"];

let result = data.filter(s => s.startsWith('http://mywebsite.com/'));

console.log(result);

As mentioned in your comment; if you wants to check multiple strings then you can try this:

let data = ["http://mywebsite.com/search",
            "http://mywebsite.com/find",
            "http://yourwebsite.com/search",
            "http://yourwebsite.com/find"];

let strToMatch = ["http://mywebsite.com/search", "http://mywebsite.com/find"];

let result = data.filter(s1 => strToMatch.some(s2 => s2.startsWith(s1)));

console.log(result);

Docs:

  • String.prototype.startsWith()
  • Array.prototype.filter()
  • Arrow Functions


回答2:

Use Array filter() method You can make a simple function and pass that array of string and check what you want in it exist or not

var yourString = ["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"];

function specificString(yourString ) {
    return yourString === "http://mywebsite.com/search";
}
console.log(specificString(yourString));