2

My question is how to get index of array which contains/includes string value. See my code below to get the result I want.

This is simple code to get index of array:

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles"));
console.log(arraycontainsturtles) // the result will be 2

I want to get the index result with a code sample below:

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turt"));
console.log(arraycontainsturtles) // i want the result will be 2 with the contains string just the 'turt' only. 

How to get the index with a contains string value like at the sample number 2? The real result of the number 2 will be -1.

How do I do that?

0

4 Answers 4

1

Use findIndex instead of indexOf, as you can provide a function.

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.findIndex(function(item){
    return item.indexOf("turt")!==-1;
}));
console.log(arraycontainsturtles) // 2

Sign up to request clarification or add additional context in comments.

1 Comment

thanks it solved. another answer is good. but this code is very simple .. thanks @Kevin Drost
0

var myarr = ["I", "like", "turtles"];
    var arraycontainsturtles = -1;
    for(i=0;i<myarr.length;i++){
    if((myarr[i].indexOf("turt")) != -1){
           arraycontainsturtles = i;
    }
    }
    console.log(arraycontainsturtles)

2 Comments

It works in this case, but does not return the first index when "turt" exists more than once in the array
@KevinDrost, there is no proper req in question to get only first index. off you can use break to come out the loop ,after find out the index.
0

Hope this is what your looking for

var myarr = ["I", "like", "turtles"];
var search = "turt";
var arraycontainsturtles = myarr.reverse().reduce((a, v, i) => v.indexOf(search) != -1 ? Math.abs(i - myarr.length + 1) : a, -1);
console.log(arraycontainsturtles)

Comments

0
var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = function(arr, str){
  let filter = -1;
  filter = arr.findIndex((e) => {
     return e.indexOf(str) > -1 ; 
  });
 return filter;
}

console.log(arraycontainsturtles(myarr, "turt")) 

Comments

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.