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)
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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.

Comments

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");
});

Comments

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 Comments

Note: your i variable is global.
@gcampbell wouldn't all these variables be global not just i? :) see here, jsfiddle.net/uft4vaoc/6
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.