Radex
Radex

Reputation: 8587

How to use properly JS includes

I have the following script, I have an array and I need to filter my a specific keywords, in this case GitHub, the code result false, when instead I need to tweak it to return true.

What am I doing wrong? How to fix it?

const array1 = ["[GitHub](https://github.com/xxx", 2, 3];

console.log(array1.includes('GitHub'));

Upvotes: 0

Views: 63

Answers (2)

Rajesh
Rajesh

Reputation: 24925

As commented .includes is not the intended feature. It does exact search and you are looking for a partial search.

array.some + String.includes

As correctly pointed out by @Nick Parsons, since numbers do not have .includes, we will have to convert it to string.

just a heads up, with the first snippet, if a number appears before a valid match it will throw an error.

const array1 = [5, "[GitHub](https://github.com/xxx", 2, 3];

console.log(array1.some((str) => str.toString().includes('GitHub')));


String.includes

If you have primitive values in array, you can directly use string.includes

As commented by @Max

"partial search" is rather misleading term. Search by predicate is what it really is

const array1 = ["[GitHub](https://github.com/xxx", 2, 3];

console.log(array1.join().includes('GitHub'));

Note, sytring.includes is a case sensitive function and will fail for mismatching case.

If you wish to have case insensitive search, either transform both string values to same case or use regex

const array1 = ["[GitHub](https://github.com/xxx", 2, 3];

function test(str) {
  const regex = new RegExp(str, 'i')
  console.log(regex.test(array1.join()));
}

test('GitHub')
test('git')
test('hub')

Upvotes: 3

Quentin
Quentin

Reputation: 943639

See the documentation:

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

While "GitHub" is a substring of one of the values, it is not an exact match for that value. You cannot use includes for this.


The find method allows you to pass a function which could do a substring match (using the includes method of a String.

const array1 = ["[GitHub](https://github.com/xxx", 2, 3];
const results = array1.find(element => element.includes('GitHub'));
const match = !!results; // Convert to boolean

console.log(results);
console.log(match);

Upvotes: 0

Related Questions