0

Suppose my array is ["abcdefg", "hijklmnop"] and I am looking at if "mnop" is part of this array. How can I do this using a javascript method?

I tried this and it does not work:

var array= ["abcdefg", "hijklmnop"];
console.log(array.indexOf("mnop")); //-1 since it does not find it in the string
0

5 Answers 5

3
var array= ["abcdefg", "hijklmnop"];
var newArray = array.filter(function(val) {
    return val.indexOf("mnop") !== -1
})
console.log(newArray)
1
  • or array.some() if you only need to know wether there is a match or not. Because some() can stop iterating as soon as it has a match.
    – Thomas
    Commented Aug 5, 2016 at 22:58
1

a possible solution is filtering the array through string.match

var array= ["abcdefg", "hijklmnop"];

var res = array.filter(x => x.match(/mnop/));

console.log(res)

1

You can use Array#some:

// ES2016
array.some(x => x.includes(testString));

// ES5
array.some(function (x) {
  return x.indexOf(testString) !== -1;
});

Note: arrow functions are part of ES6/ES2015; String#includes is part of ES2016.

The Array#some method executes a function against each item in the array: if the function returns a truthy value for at least one item, then Array#some returns true.

0
0

Javascript does not provide what you're asking before because it's easily done with existing functions. You should iterate through each array element individually and call indexOf on each element:

array.forEach(function(str){
    if(str.indexOf("mnop") !== -1) return str.indexOf("mnop");
});
0

Can be done like this https://jsfiddle.net/uft4vaoc/4/

Ultimately, you can do it a thousand different ways. Almost all answers above and below will work.

<script>
var n;
var str;
var array= ["abcdefg", "hijklmnop"];
//console.log(array.indexOf("mnop")); //-1 since it does not find it in the string
for (i = 0; i < array.length; i++) { 
    str = array[i];
    n = str.includes("mnop");
    if(n === true){alert("this string "+str+" conatians mnop");}
}
</script>
3
  • Note: your i variable is global.
    – gcampbell
    Commented Aug 5, 2016 at 22:44
  • @gcampbell wouldn't all these variables be global not just i? :) see here, jsfiddle.net/uft4vaoc/6 Commented Aug 5, 2016 at 22:46
  • i here is an implied global: people usually write for (var i = 0; rather than for (i = 0;. It becomes an issue if you have code inside the loop that also changes the global i variable.
    – gcampbell
    Commented Aug 5, 2016 at 22:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.