Skip to content Skip to sidebar Skip to footer

Check If An Array Of Strings Contains A Substring

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 di

Solution 1:

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)

Solution 2:

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 left) 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.


Does any element match the predicate?

const array = ["123", "456", "#123"];
console.log(array.some(e => e.includes("#"))); // trueconsole.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("#"))); // falseconsole.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("#"))); // 2console.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 are the indices of all of the elements that match the predicate?

constfilterIndices = (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()

What is the last element that matches the predicate?

constfindLast = (a, pred) => {
  for (let i = a.length - 1; i >= 0; i--) {
    if (pred(a[i], i, a)) {
      return a[i];
    }
  }
};

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

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

constfindLastIndex = (a, pred) => {
  for (let i = a.length - 1; i >= 0; i--) {
    if (pred(a[i], i, a)) {
      return i;
    }
  }

  return -1;
};

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

Solution 3:

You can use join method:

array.join('').indexOf("#")

Solution 4:

Use Array.some:

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

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

Solution 5:

You can use filter ().

vararray = ["123", "456", "#123"];

    console.log(array.filter(function(item){
        var finder = '#';
        returneval('/'+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.

Post a Comment for "Check If An Array Of Strings Contains A Substring"