Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter strings in Array based on content (filter search value)

Tags:

I am running into an issue, I have a similar array of Strings in JS:

var myArray = ["bedroomone", "bedroomonetwo", "bathroom"]; 

And I would like to retrieve all the elements in the array that contains the keyword 'bedroom'. How can I achieve such result ?

I tried in different ways without getting the desired result. How should I proceed ?

like image 304
prince Avatar asked Feb 06 '16 00:02

prince


People also ask

How do you filter an array based on string?

To filter strings of an Array based on length in JavaScript, call Array. filter() method on this String Array, and pass a function as argument that returns true for the specific condition on string length or false otherwise.

Can you use filter on a string?

You can't use filter() on a string as it is an Array.


2 Answers

String.prototype.indexOf:

var PATTERN = 'bedroom',     filtered = myArray.filter(function (str) { return str.indexOf(PATTERN) === -1; }); 

Regexp:

var PATTERN = /bedroom/,     filtered = myArray.filter(function (str) { return PATTERN.test(str); }); 

String.prototype.includes (only in moderm browsers):

var PATTERN = 'bedroom',     filtered = myArray.filter(function (str) { return str.includes(PATTERN); }); 
like image 59
Microfed Avatar answered Sep 27 '22 20:09

Microfed


var bedrooms = myArray.filter(name => name.includes('bedroom')) 
like image 38
Ania Zielinska Avatar answered Sep 27 '22 20:09

Ania Zielinska