How to determine the cheapest and fastest rate and get the value in single object.
cheapest
is determined by usingnetfee
havingleast value
fastest
is determined by usingspeed
havingless days
best
is determined by usingamount
havinghighest value
I got stuck and let know is any alternative solution.
var result = getValue(obj); getValue(obj){ var cheapest= Math.min.apply(Math, obj.map(function (el) { return el.netfee; })); var best= Math.max.apply(Math, obj.map(function (el) { return el.amount; })); var res= Object.assign({}, cheapest, best); return res; }
var obj=[ { id: "sample1", netfee: 10, speed: "1days", amount: "100" }, { id: "sample2", netfee: 6, speed: "2days", amount: "200" }, { id: "sample3", netfee: 4, speed: "3days", amount: "50" } ] Expected Output: Cheapest : Sample 3 Fastest: Sample 1 Best: Sample 2
Advertisement
Answer
so simple..
var obj=[ { id: "sample1", netfee: 10, speed: "1days", amount: "100" }, { id: "sample2", netfee: 6, speed: "2days", amount: "200" }, { id: "sample3", netfee: 4, speed: "3days", amount: "50" } ]; var cheapest = obj.reduce((acc, cur)=>(acc.netfee < cur.netfee ? acc : cur)).id, fastest = obj.reduce((acc, cur)=>(parseInt(acc.speed,10) < parseInt(cur.speed,10) ? acc : cur)).id, best = obj.reduce((acc, cur)=>(Number(acc.amount) > Number(cur.amount) ? acc : cur)).id; console.log( "cheapest =", cheapest ) console.log( "fastest =", fastest ) console.log( "best =", best )
[edit]:
Thanks to muka.gergely for his remark on parseInt(acc.speed,10)
(specify to use base 10)
for memo : console.log(parseFloat('0.7 days')
return = 0.7