Bilal Hussain Bilal Hussain - 1 year ago 85
jQuery Question

Check inArray dynamically

I have stuck somewhere, may be it's the simplest question but I had tried googling as much as I can and didn't find the exact result.


  • I have a simple calendar, added by HTML, jquery

  • In my woocomerce/WordPress site, I want to show the booked number of products based on booking start and end date on the calendar. Something like when a user hovers on the dates on the calendar, the number of booked products would show underneath date. (I am developing a rent website which takes dates range from start to end, just like hotels, this can be ignored.)

  • The calendar is showing fine for one product as shown in image
    enter image description here



BUT if in case say for August 18, we have two products booked, I want to show there "2 booked"

for this, I am using inArray function.


  • I have an array of dates (var only_dates)

  • I have the current dates (var some)[inside the range of start and end]



I have tried
console.log(jQuery.inArray(some, only_dates))


and this is giving me the result
enter image description here
As screenshot, we have 18-August already, so in the second time, I want to count it as 2 & then same for 19-August too & so on.

for one object we can try by

if(jQuery.inArray(some, only_dates) == 1)
{
console.log('found')
}


but in my case, how can I use inArray for dynamically in loop (for more than) and then print the number of occurance.

Any help would be appreciated. Thanks.

EDIT:
So Here's my code

$sepr_date = getDatesFromRange($start, $end); /*a function that coverts range dates into sequence*/
foreach ($sepr_date as $dt) {?>
<script type="text/javascript">
ds = {'Date': new Date("<?php echo $dt; ?>"), 'Title': 'Booked', 'Link': 'javascript:void(0)'},
events_s.push(ds)
var some = "<?php echo $dt; ?>"
only_dates.push(some)
console.log(some)
console.log(only_dates)
if(jQuery.inArray(some, only_dates) != -1)
{
console.log('found ' + some)
}
</script>
<?}?>


console giving :

enter image description here

While pushing item, I wanna check existence.
and if found, increment count.
If not found, do nothing as simple as that.

Answer Source

You can use grep function:

var count = $.grep(only_dates, function (elem) {
    return elem === some;
}).length;

https://stackoverflow.com/a/5658562/7604006

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download