Filter Strings in Array Based on Content (Filter Search Value)

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 ?

8

5 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); });
1
var bedrooms = myArray.filter(name => name.includes('bedroom'))
1

Improved Microfed's answer to this

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

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 
1

You could also use the search() method

Finds the first substring match in a regular expression search.

(method) String.search(regexp: string | RegExp): number (+1 overload)

const filterList = (data, query) => {
        return data.filter(name => name.toLowerCase().search(query.toLowerCase()) !== -1);
      };

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.