Quantcast
Viewing latest article 39
Browse Latest Browse All 66

Answer by Md. Harun Or Rashid for How do I check if an array includes a value in JavaScript?

This may be a detailed and easy solution.

//plain arrayvar arr = ['a', 'b', 'c'];var check = arr.includes('a');console.log(check); //returns trueif (check){   // value exists in array   //write some codes}// array with objectsvar arr = [      {x:'a', y:'b'},      {x:'p', y:'q'}  ];// if you want to check if x:'p' exists in arrvar check = arr.filter(function (elm){    if (elm.x == 'p')    {       return elm; // returns length = 1 (object exists in array)    }});// or y:'q' exists in arrvar check = arr.filter(function (elm){    if (elm.y == 'q')    {       return elm; // returns length = 1 (object exists in array)    }});// if you want to check, if the entire object {x:'p', y:'q'} exists in arrvar check = arr.filter(function (elm){    if (elm.x == 'p'&& elm.y == 'q')    {       return elm; // returns length = 1 (object exists in array)    }});// in all casesconsole.log(check.length); // returns 1if (check.length > 0){   // returns true   // object exists in array   //write some codes}

Viewing latest article 39
Browse Latest Browse All 66

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>