Saturday 21 December 2019

javascript - Jquery, checking if a value exists in array or not




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)});
}

Answer




If you want to do it using .map() or just want to know how it works you can do it like this:



var added=false;
$.map(arr, function(elementOfArray, indexInArray) {
if (elementOfArray.id == productID) {
elementOfArray.price = productPrice;
added = true;
}
}
if (!added) {

arr.push({id: productID, price: productPrice})
}


The function handles each element separately. The .inArray() proposed in other answers is probably the more efficient way to do it.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...