在JavaScript中比较和筛选对象数组

3
如何确定最便宜和最快的费率并获得单个对象中的价值。
  • 通过使用netfee,其中least value决定了cheapest
  • 通过使用speed,其中less days决定了fastest
  • 通过使用amount,其中highest value决定了best
我卡住了,请告诉我是否有其他替代方案。
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
2个回答

3
如此简单...

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  )

[编辑]: 感谢muka.gergely指出parseInt(acc.speed,10)(指定使用十进制)
备忘录:console.log(parseFloat('0.7 days') 返回值为0.7


不要在没有设置基数的情况下使用 parseInt,例如 **parseInt(acc.speed, 10)**。这样可以节省大量调试时间和“到底发生了什么?”类型的问题。 - muka.gergely
@muka.gergely 我认为如果 parseInt 方法的 string 参数不以 0x0 开头,则 radix 参数默认为10?️ - Aminu Kano
可能是这样,但在这段代码中并没有保证 - 你可以将速度设置为0.5天(只要代码允许),最好还是安全第一 :) - muka.gergely
哦,是的,你有理 :) - Aminu Kano

1
你可以应用这个技巧,使得答案与期望输出一致:

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);


1
返回 { 最便宜的,最快的,最好的 }; - Mister Jojo
关于编程的内容:使用+acc.amount比使用Number(acc.amount)更慢。请注意,本文仅为翻译,不涉及任何解释。 - Mister Jojo
@MrJ 真的吗??jsperf.com 告诉我不一样,看看这里:链接 - Aminu Kano
我认为在这种情况下这种性能测试并不有效。这个测试应该只做少于10次循环,使用来自表格的数字,以及负值;这样我们才能更好地评估解释器JS的工作,而不会让它启动操作优化器。 - Mister Jojo
哦,是的,我理解你的观点。 - Aminu Kano

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接