在JavaScript中比较和过滤对象数组

时间:2019-04-11 04:37:11

标签: javascript jquery arrays object

如何确定最便宜和最快的价格并获得单个对象的价值。

  • cheapest通过使用具有netfee的{​​{1}}来确定
  • least value通过使用具有fastest的{​​{1}}来确定
  • speed通过使用具有less days的{​​{1}}来确定

我被卡住了,让我们知道还有其他解决方法。

best
amount

2 个答案:

答案 0 :(得分: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) (指定使用10为底)的评论
 备忘:console.log(parseFloat('0.7 days')返回= 0.7

答案 1 :(得分: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);