43

I have an array like this:

array = ["123", "456", "#123"]

I want to find the element which contains the substring "#". I tried array.includes("#") and array.indexOf("#") but it didn't work.

How can I check if any of the strings in this array contain the substring "#"?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
RamAlx
  • 6,976
  • 23
  • 58
  • 106

5 Answers5

75

Because includes will compare '#' with each array element.

Let's try with some or find if you want to find if you want to get exactly element

var array = ["123", "456", "#123"];

var el = array.find(a =>a.includes("#"));

console.log(el)
taile
  • 2,738
  • 17
  • 29
  • 4
    the "some" method is very useful for a case such as this – joey8oro Jun 11 '19 at 19:07
  • Using "some" https://stackoverflow.com/questions/16312528/check-if-an-array-contains-any-element-of-another-array-in-javascript – king Jul 27 '21 at 03:14
  • this only find 1st occurence. i wnt to get all ocurrences – shorif2000 Apr 10 '22 at 15:50
  • let's use `map` instead of `find` for your demand @shorif2000 `var el = array.map(a => a.includes("#") ? a : false).filter(Boolean);` – taile Apr 11 '22 at 09:30
  • What @taile you would do, if the case is vice versa. eg. var array = ["123", "456", "#123"]; and we have '1234' for comparison. As first 3 chars '123' are in array. This should return ['123', '#123]. How can we achieve this? – Vishal Kumar Dec 07 '22 at 08:54
  • 1
    you should use filter in this case @VishalKumar `array.filter(a =>a.includes("123"));` – taile Dec 07 '22 at 11:38
17

There appears to be multiple questions here since the title and post body differ. Do you want to know if the array has an element or do you want to get the element itself? If you want to get an element, which one(s) do you want--the first occurrence, the last occurrence or an array of all occurrences?

This post is intended as a resource for future visitors who might not necessarily want to find (i.e. return the first element from the start of the array that matches a predicate) as the top answer shows. To elaborate on that answer, there's a gotcha with indiscriminately replacing some with find in a boolean context--the element returned may be falsey as in

if ([5, 6, 0].find(e => e < 3)) { // fix: use `some` instead of `find`
  console.log("you might expect this to run");
}
else {
  console.log("but this actually runs " +
    "because the found element happens to be falsey");
}

Note that e => e.includes("#") can be substituted with any predicate, so it's largely incidental to the question.

The same problem can occur when using indexOf in a condition and failing to account for the fact that 0 (the element was found at the first position in the array) is falsey.


Does any element match the predicate?

const array = ["123", "456", "#123"];
console.log(array.some(e => e.includes("#"))); // true
console.log(array.some(e => e.includes("foobar"))); // false

MDN: Array.prototype.some()

Does every element match the predicate?

const array = ["123", "456", "#123"];
console.log(array.every(e => e.includes("#"))); // false
console.log(array.every(e => /\d/.test(e))); // true

MDN: Array.prototype.every()

What is the first element that matches the predicate?

const array = ["123", "456", "#123", "456#"];
console.log(array.find(e => e.includes("#"))); // "#123"
console.log(array.find(e => e.includes("foobar"))); // undefined

MDN: Array.prototype.find()

What is the index of the first element that matches the predicate?

const array = ["123", "456", "#123", "456#"];
console.log(array.findIndex(e => e.includes("#"))); // 2
console.log(array.findIndex(e => e.includes("foobar"))); // -1

MDN: Array.prototype.findIndex()

What are all the elements that match the predicate?

const array = ["123", "456", "#123", "456#"];
console.log(array.filter(e => e.includes("#"))); // ["#123", "456#"]
console.log(array.filter(e => e.includes("foobar"))); // []

MDN: Array.prototype.filter()

What is the last element that matches the predicate?

const array = ["123", "456", "#123", "456#"];
console.log(array.findLast(e => e.includes("#"))); // "456#"
console.log(array.findLast(e => e.includes("foobar"))); // undefined

MDN: Array.prototype.findLast()

What is the index of the last element that matches the predicate?

const array = ["123", "456", "#123", "456#"];
console.log(array.findLastIndex(e => e.includes("#"))); // 3
console.log(array.findLastIndex(e => e.includes("foobar"))); // -1

MDN: Array.prototype.findLastIndex()

What are the indices of all of the elements that match the predicate?

const filterIndices = (a, pred) => a.reduce((acc, e, i) => {
  pred(e, i, a) && acc.push(i);
  return acc;
}, []);

const array = ["123", "456", "#123", "456#"];
console.log(filterIndices(array, e => e.includes("#"))); // [2, 3]
console.log(filterIndices(array, e => e.includes("foobar"))); // []

MDN: Array.prototype.reduce()

ggorlen
  • 44,755
  • 7
  • 76
  • 106
2

Use Array.some:

array.some((item) => item.includes('#'));

It just checks if some item includes '#' - readable and clear.

1

You can use join method:

array.join('').indexOf("#")
cigien
  • 57,834
  • 11
  • 73
  • 112
Mohanad Walo
  • 384
  • 3
  • 6
-1

You can use filter ().

    var array = ["123", "456", "#123"];

    console.log(array.filter(function(item){
        var finder = '#';
        return eval('/'+finder+'/').test(item);
    }));

By passing a function you can filter and return the elements that match what you are looking for.

In this example, I made use of eval (), just because to fetch the string use RegExp, but could fetch with the == operator.

GeekSilva
  • 481
  • 1
  • 5
  • 20
  • 5
    why eval? {}{}{{} – shinzou Apr 24 '18 at 13:31
  • Use `new RegExp()` instead of `eval`, or even better just use `includes`. If the substring happens to have special regex characters, the regex approach breaks, so this answer is pretty broken on a couple of levels. – ggorlen May 02 '21 at 00:25