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

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 ?


Solution 1:

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

Solution 2:

var bedrooms = myArray.filter(name => name.includes('bedroom'))

Solution 3:

Improved Microfed's answer to this

var textToSearch = 'bedroom';
var filteredArray = myArray.filter((str)=>{
  return str.toLowerCase().indexOf(textToSearch.toLowerCase()) >= 0; 
});

Solution 4:

Using JavaScript arrow function is much simpler

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

// search using keyword from array

var keywordToSearch = 'Arslan'; // word to search
var keyword =   keywordToSearch.toLowerCase();
var names = [{id: 1, name: 'Aqib'}, {id: 2, name: 'Arslan'}];

//search keyword from names array by name
var searchResult = names.filter(word => word.name.toLowerCase().indexOf(keyword) > -1);
console.log(searchResult);
// expected output: > Array [Object { id: 2, name: "Arslan" }]
Using javascript arrow function