First of all I'm aware of the multiple topics concerning this issue. But I just can't find the reason why it doesn't work in my case.
I'm trying to find the nearest highest value qty
in an array. This array is dynamically created.
So in below example the current value/quantity is 17
. I want to return from the array the object containing qty: 60
.
Whatever I try the output is undefined
. I just can't see why that is.
<div class="product" data-url="some-url-to-json" data-quantity="17">
....
</div>
$(function(){
$('#form-pagecart .product').each(function(){
var url = $(this).data('url') + '?format=json';
var cur_qty = $(this).data('quantity')
var highestArray= []
$.getJSON(url, function(data){
$.each(data.product.discounts, function(index, disc) {
highestArray.push({ qty: parseInt(disc.quantity), price: disc.price.price_incl, price_excl: disc.price.price_excl })
});
});
/* things I tried ======> */
var output = highestArray.slice().reverse().find(({ qty }) => qty <= cur_qty);
var nearest = highestArray.sort(function(a, b){
return Math.abs(a.qty - cur_qty) - Math.abs(b.qty - cur_qty)
})[0];
console.log(output, nearest)
});
When I console.log highestArray
I get:
[
{
"qty": 15,
"price": 18.1379,
"price_excl": 14.99
},
{
"qty": 60,
"price": 16.3229,
"price_excl": 13.49
},
{
"qty": 120,
"price": 15.1129,
"price_excl": 12.49
},
{
"qty": 240,
"price": 14.5079,
"price_excl": 11.99
}
]
Why keeps console.log returning undefined
then for output
and nearest
?
I aslo tried using a function like:
changePrice(highestArray, cur_qty)
function changePrice(array,num){
var output = array.slice().reverse().find(({ qty }) => qty <= num);
if(output){
$('.price .price-new i').text(output['price'])
$('.price .vat i').text(output['price_excl'])
}
}