admitme_sam admitme_sam - 3 months ago 5
Javascript Question

How to get the highest and lowest number

So i have this set of code which looks like this

for (var i = 0; i < secname.length; i++) {
description = secname[i].description
price = secname[i].price_breakdown.display_charges.price
debugger;
}


What my issue is at the moment is that this passes back 3-4 prices per object.

What ideally i'm wanting is the lowest and the highest price from these with the description. It currently passes back (with the same description) 4 prices before going into the next description.

I would also like to put it into the table i have. i have the prepend code i'm just unsure where to place it.

So tl;dr I have a table, The description name is unique and has 4 prices. I want the highest price and lowest price appended to my table.

Sam

Edit

Heres the code

"CIRCLE": [
{
"price_secname": "P1",
"price_breakdown": {

"price_secname": "P1",
"vat": 0,
"distance_charge": 0,
"display_charges": {
"price": 35,
"sum_fees": "5.25",
"formatted_total_price": "&Acirc;&pound;40.25"
},

"legacy_price": 35
},

"description": "Circle",
"ticket_desc": "Full Price Ticket",

},
{
"price_secname": "P2",
"price_breakdown": {

"price_secname": "P2",
"vat": 0,
"distance_charge": 0,
"display_charges": {
"price": 50,
"sum_fees": "5.25",
"formatted_total_price": "&Acirc;&pound;50.25"
},

"legacy_price": 35
},

"description": "Circle",
"ticket_desc": "Full Price Ticket",

},
{
"price_secname": "P3",
"price_breakdown": {

"price_secname": "P3",
"vat": 0,
"distance_charge": 0,
"display_charges": {
"price": 40,
"sum_fees": "5.25",
"formatted_total_price": "&Acirc;&pound;45.25"
},

"legacy_price": 40
},

"description": "Circle",
"ticket_desc": "Full Price Ticket",

}
]

Answer

Just building off Rejesh answer, essentially looping over each object and pulling out the max, min and description.

for (var i = 0; i < circle.length; i++) {
    var description = circle[i].description
    var price = circle.map(function(x){ return x.price_breakdown.display_charges.price; }); 
    var max = Math.max.apply(null, price); 
    var min = Math.min.apply(Math, price.filter(Number));
    console.log(description)
    console.log("Max: " + max);
    console.log("Min: " + min);    
}

Snippit

http://jsbin.com/vodifemodo/edit?html,js,output

Comments