Anthony LoPrimo
Anthony LoPrimo

Reputation: 147

Using filter() to test an array against another array of unknown size

I'm messing around with the the example code on the MDN page detailing Array.prototype.filter(), and I'm finding something interesting happening.

I modified the example code to be the following:

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.includes('e', 'i'));

console.log(result);
// expected output: const result = words.filter(word => word.includes('e', 'i'));

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

And it works, however when I modify it so those two characters are located in a variable (either declared with const OR var)...

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
var test = ['e', 'i'];
const result = words.filter(word => word.includes(test));

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

Lastly, if I change test to test[0,1] I get the first result - as expected.

Other similar looking questions didn't seem to help me, and I'm not quite sure what's happening here, or how I can make this work.

Upvotes: 0

Views: 101

Answers (1)

oligofren
oligofren

Reputation: 22923

The problem is that the version with a variable does not do the same thing as the version that has no variable.

word.includes('e', 'i') is not the same as word.includes(['e', 'i']) (although neither do what you think, as noted below).

If you want store your arguments in an array and have them applied as multiple arguments (spread out) in your function call , instead of as a single array argument, you can use the spread syntax:

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
var test = ['e', 'i'];
const result = words.filter(word => word.includes(...test));

console.log(result);

The real issue

The real issue here is that you are not calling the function correctly. Check the MDN Docs for String#includes:

includes(searchString)

searchString A string to be searched for within str.

This function only takes a single parameter. So when you word.includes('e', 'i'), you should not expect it to match on words that has "i" in them. Only "e".

If you want to match on words that contain all of the strings you want to match against, you need to redo your logic:

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

const containsAll = words.filter( word => test.every (str => word.includes(str)))
const oneOf = words.filter( word => test.some (str => word.includes(str)))

console.log(containsAll);
console.log(oneOf);

Upvotes: 1

Related Questions