-1

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.

David
  • 4,266
  • 8
  • 34
  • 69
  • this might be a duplicate, check this [http://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object](http://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object) – Nicholas Mar 22 '17 at 09:58
  • It's var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"]; or var arr = [abc="0",def="2",ghi="3",jkl="6",mno="9"]; ? – Marco Salerno Mar 22 '17 at 09:59

6 Answers6

3

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 ^^

Marco Salerno
  • 5,131
  • 2
  • 12
  • 32
2

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
pdonias
  • 69
  • 1
  • 3
1

Using lodash

var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
var r = _.find(arr, function(i) { return i.includes('ghi'); });
alert(r);

DEMO

mtefi
  • 117
  • 1
  • 9
1

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.

ytibrewala
  • 957
  • 1
  • 8
  • 12
1

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);
}
Nitha
  • 672
  • 5
  • 10
1

the best and simple logic is:

arr.find(function(item) {
   return (typeof item === "string" && item.includes("ghi"));
});
Suneel K
  • 84
  • 1
  • 9