How to determine the cheapest and fastest rate and get the value in single object.
cheapest is determined by using netfee having least value fastest is determined by using speed having less daysbest is determined by using amount having highest valueI 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
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
You can apply this hack, to have the answer as in the expected output:
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 result = getValue(obj);
function getValue(obj) {
var cheapest = obj.reduce((acc, next) => acc.netfee < next.netfee ? acc : next).id;
var fastest = obj.reduce((acc, next) => parseInt(acc.speed) < parseInt(next.speed) ? acc : next).id;
var best = obj.reduce((acc, next) => +acc.amount > +next.amount ? acc : next).id;
var res = Object.assign({}, {
cheapest,
fastest,
best
});
return res;
}
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With