-1

i need to check a specific string exist in jquery array . For this i write the following code .But it is not working . Please help .

$(document).ready(function() {
    var ar = ["color1:white", "color2:black"];

    if ($.inArray("black", ar) > -1) {
        alert("yes");
    } else {
        alert("no");
    }
});

.I need to check black color is in the array. Please help.

5
  • what is a jquery array? Commented Jan 17, 2017 at 8:00
  • sorry , what is the error in my code ? i didn't understand .
    – Jafar tm
    Commented Jan 17, 2017 at 8:03
  • inArray i already used
    – Jafar tm
    Commented Jan 17, 2017 at 8:04
  • You could also check by inclusion and directly with .forEach()
    – Joshua
    Commented Jan 17, 2017 at 8:11
  • could you please give example.
    – Jafar tm
    Commented Jan 17, 2017 at 8:12

2 Answers 2

1

No need to use jquery:

var arr = ["color1:white","color2:black"].map(x => x.split(':')[1]);

console.log(arr); 
console.log(arr.indexOf('black') > -1 ? 'yes' : 'no');

2
  • array contain many value , not only this two values . for example var ar = ["color1:white", "color2:black", "color3:red:yes", "class-test:div:append"];
    – Jafar tm
    Commented Jan 17, 2017 at 8:09
  • @Jafartm Then, trying to use forEach() method. Something like: arr.forEach(x => console.log(x.indexOf('substring')));
    – Tân
    Commented Jan 17, 2017 at 8:12
0

Please check if you have properly assigned values to an array. Try below code:

if ($.inArray("black", ar) !== -1) {
   alert("yes");
}
else {
   alert("no");
}
1
  • This isn't how $.inArray works at all Commented Jan 17, 2017 at 8:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.