41

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 ?

Tan Nguyen
  • 323
  • 2
  • 14
prince
  • 449
  • 2
  • 5
  • 6
  • 2
    Where is the code that you tried? – Pointy Feb 06 '16 at 00:29
  • 1
    var resultsfilter = myArray.filter(function (element) { return element !== "bedroom"}); console.log(resultsfilter); – prince Feb 06 '16 at 00:31
  • 1
    `!==` does an exact comparison. You need something like `/bedroom/.test(element)` – Pointy Feb 06 '16 at 00:32
  • 1
    String.indexOf is good enough. You don't need a regex for that. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf – Microfed Feb 06 '16 at 00:33
  • 1
    var resultsfilter = myArray.filter(function (element) { return /bedroom/.test(element)}); ???? – prince Feb 06 '16 at 00:34
  • Right, or `.indexOf()` - the performance differences are uninteresting in general so use whichever you think is prettier. – Pointy Feb 06 '16 at 00:35
  • I used this: `var resultsfilter = myArray.filter(function (element) { return element.indexOf("bedroom") > -1});` but it shows only these items: `"bedroomone", "bedroomonetwo"`, I mean what I dont need. – prince Feb 06 '16 at 00:37
  • Then `return !/bedroom/.test(element)` – Pointy Feb 06 '16 at 01:08

6 Answers6

69

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); });
Microfed
  • 2,832
  • 22
  • 25
54
var bedrooms = myArray.filter(name => name.includes('bedroom'))
Zoe
  • 27,060
  • 21
  • 118
  • 148
Ania Zielinska
  • 641
  • 5
  • 2
6

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 
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Arslan Butt
  • 775
  • 1
  • 8
  • 20
5

Improved Microfed's answer to this

var textToSearch = 'bedroom';
var filteredArray = myArray.filter((str)=>{
  return str.toLowerCase().indexOf(textToSearch.toLowerCase()) >= 0; 
});
Moh .S
  • 1,920
  • 19
  • 19
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);
      };
Ardenne
  • 897
  • 2
  • 13
  • 23
1
const House = ["bedroomone", "bedroomtwo", "bathroom"]
const filterItems = (arr, query) => {
    return arr.filter(element => 
    element.toLowerCase().indexOf(query.toLowerCase()) !== -1)
}
console.log(filterItems(House, "bedroom"));
Henry
  • 11
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 07 '22 at 19:21