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?
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?
Share Improve this question edited Apr 11, 2018 at 10:43 Didi Rumapea asked Apr 11, 2018 at 10:05 Didi RumapeaDidi Rumapea 551 gold badge1 silver badge6 bronze badges 04 Answers
Reset to default 1Use 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
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)
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)
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"))