Skip to content
Advertisement

Compare and Filter Object Array in javascript

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 days
  • best is determined by using amount having highest 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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement