0

I need to check each element of an array for a certain letter. if the element contains this letter it should stay within the array, if it does not it should be removed.

currently I'm able to remove elements if they are exact, but not sure how to go about checking each index of each element.

var exampleList = ['alpha', 'beta','dog']

exampleList.filter(function(word) {
    return (word == 'dog');
})

my end goal would be something like this.

letterToInclude = 'a'
var exampleList = ['alpha', 'beta','dog', 'mouse']

exampleList.filter(function(word) {
    return (word == letterToInclude);
})
// returned values = ['alpha', 'beta']
Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
Pyreal
  • 517
  • 3
  • 8
  • 19
  • 1
    `list.filter(word => word.includes(letter))` – Aᴍɪʀ Jan 17 '17 at 21:14
  • i like `['alpha','beta','dog'].filter(/./.test, RegExp( "a" ));`, but you can write out the functions manually if desired; a lot of people don't understand generic recycling... – dandavis Jan 17 '17 at 21:18

4 Answers4

3

Instead of doing ==, you can use indexOf to see if letterToInclude occurs in word.

letterToInclude = 'a'
var exampleList = ['alpha', 'beta','dog', 'mouse']

exampleList.filter(function(word) {
    return (word.indexOf(letterToInclude) > -1);
});

indexOf returns the position that letterToInclude occurs in word; in the event it is not found, indexOf will return -1.

The reason I didn't use word.includes(letterToInclude) is just for compatibility purposes. includes is fairly new and isn't completely supported.

Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
1

You can use indexOf() to check if each element contains a specific letter.

var letterToInclude = 'a'
var exampleList = ['alpha', 'beta', 'dog', 'mouse']

exampleList = exampleList.filter(function(word) {
  return word.indexOf(letterToInclude) != -1
})

console.log(exampleList)

ES6 solution with String#includes(), also you can use match() or test() but those take regular expressions.

exampleList.filter(word => word.includes(letterToInclude))
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

Try using indexOf:

letterToInclude = 'a'
var exampleList = ['alpha', 'beta','dog', 'mouse']

console.log(exampleList.filter(function(word) {
    return ~(word.indexOf(letterToInclude));
}));
cyberbit
  • 1,345
  • 15
  • 22
0

It works well together with Unicode chars:

var lettersToInclude = 'aa'
var exampleList = ['a', 'aa','❤✓☀a★bAb', 'bbaa', 'aa☂']

var r = exampleList.filter(function(word) {
    return (word.indexOf(lettersToInclude) > -1);
});

console.log(r);
prosti
  • 42,291
  • 14
  • 186
  • 151