Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery, checking if a value exists in array or not [duplicate]

I believe this question will be fairly easy for the ones who played around with java script / jquery.

var arr = new Array();  $.map(arr, function() {  if (this.id == productID) {    this.price = productPrice;  }else {   arr.push({id: productID, price: productPrice})  } } 

I guess the code above explains what I want in really simple way. I would imagine this $.map would work like this but unfortunately I couldn't get results with this.

What is the most simple and elegant way to do this? Do I truly go through all array just to find if a key's value is there or not?

Does Jquery has something like isset($array['key'])?

EDIT

I tried to use inArray but it keeps adding object to array even if there is a match.

if ( $.inArray(productID, arr) > -1) {    var number = $.inArray(productID, arr);    orderInfo[number].price = parseFloat(productPrice); }else {    orderInfo.push({id:productID, price:parseFloat(productPrice)}); } 
like image 386
Revenant Avatar asked Oct 24 '11 19:10

Revenant


People also ask

How do you check if a value exists in an array in jQuery?

1) Using jQuery If you are someone strongly committed to using the jQuery library, you can use the . inArray( ) method. If the function finds the value, it returns the index position of the value and -1 if it doesn't.

How do you check if a value exists in an array JavaScript?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.

How do you check if a string exists in an array jQuery?

inArray() This jQuery array method search the the item within the array. If element exists in the jQuery array it returns the index position of the value and if the value doesn't exist then it will return -1 .

How do I check if an array contains a value?

For primitive values, use the array. includes() method to check if an array contains a value. For objects, use the isEqual() helper function to compare objects and array. some() method to check if the array contains the object.


1 Answers

http://api.jquery.com/jQuery.inArray/

if ($.inArray('example', myArray) != -1) {   // found it } 
like image 175
jbabey Avatar answered Oct 03 '22 12:10

jbabey