I have one array
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
Now I want to check whether "ghi" and "mno" is there or not in array. If there then what is the value.
I have one array
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
Now I want to check whether "ghi" and "mno" is there or not in array. If there then what is the value.
This is how to do it:
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
for(var child in arr){
console.log(arr[child].includes("mno"));
}
Edit, for old browser you can do it this way:
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
for(var child in arr){
console.log(arr[child].search("mno"));
}
Where 0 is equal to true ^^
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
function valueOf (array, key) {
var value;
if (array.find(function (item) {
return ([ , value ] = item.split("="))[0] === key
})) {
return value;
}
}
console.log(valueOf(arr, "ghi")); // 3
console.log(valueOf(arr, "mno")); // 9
console.log(valueOf(arr, "foo")); // undefined
You could use Array.prototype.find() and String.prototype.includes()
arr.find(function(item) {
if(typeof item === "string" && item.includes("asd")) {
return true;
}
return false;
});
Now if an item was found, you can assume that the string was found in the array.
Loop through the array and check each string.
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
var pos_of_ghi = searchStringInArray("ghi", arr );
var pos_of_mno = searchStringInArray("mno", arr );
if(pos_of_ghi ==-1){
alert("ghi not found")
}
else{
alert("pos_of_ghi="+pos_of_ghi);
}
if(pos_of_mno ==-1){
alert("mno not found")
}
else{
alert("pos_of_mno="+pos_of_mno);
}
the best and simple logic is:
arr.find(function(item) {
return (typeof item === "string" && item.includes("ghi"));
});