2

I have tried using the includes() function but it returns false for me as follows:

<script>
    var fruits = ["Banana-orange", "Orange", "Apple", "Mango"];
    console.log(fruits.includes("-")); // returnes false, should be true
</script>

As you can see, 'banana-orange' contains a hyphen. I expect the result to return true.

Am I using the wrong function?

Sweepster
  • 1,829
  • 4
  • 27
  • 66
  • "For arrays, the search value must match an element, You can't match a substring of an element." – B. Go Mar 31 '19 at 17:15
  • https://stackoverflow.com/questions/44440317/check-if-an-array-of-strings-contains-a-substring-in-javascript answers with filter() and find(). IE this is a duplicate of a broader question... – B. Go Mar 31 '19 at 17:16

4 Answers4

5

The Array#includes compare with the element in the array(full string match in your case). To make it work, join the values in the array with empty space(use Array#join) and use String#includes method which searches for a substring.

var fruits = ["Banana-orange", "Orange", "Apple", "Mango"];
console.log(fruits.join('').includes("-")); 

Or use Array#some to iterate and check at least one contains the string using String#includes method.

var fruits = ["Banana-orange", "Orange", "Apple", "Mango"];
console.log(fruits.some(v => v.includes("-")));
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

Use Array.some:

fruits.some((fruit) => fruit.includes('-'));

It just checks if some fruit includes hyphen - readable and clear.

0

What you are actually checking is if there is an item in the array fruits which is "-",

I would use a for loop to check, if there is an item of the array which includes '-'.

const fruits = ['Banana-orange', 'Orange', 'Apple', 'Mango'];

for (let i = 0; fruits.length; i++) {
    if (fruits[i].includes('-')) return true;
}
Gilles Heinesch
  • 2,889
  • 1
  • 22
  • 43
-1

Fruits does not include ‘-‘. Fruits(1) contains ‘-‘. This is why the includes function does not return anything. Loop through the array instead and test the contents of the array.

camba1
  • 1,795
  • 2
  • 12
  • 18