如何在JSON对象中获得两个数字之间的最大差

时间:2019-07-17 19:31:53

标签: javascript arrays node.js json

我正在与NodeJS一起在网站上创建“特色产品”小部件。我有一个SKUpricesale_price的JSON对象。获得折扣最高(价格与sale_price之间的差异)的商品SKU的最佳方法是什么?

我尝试通过遍历项目并找到price和sale_price之间的差异,将结果推送到数组然后获得最大值,来实现此目的,但是我当时无法获得SKU。

我拥有的JSON对象的示例:

{ "item_number":12341231, "price":"250", "sale_price":"219.99"},
{ "item_number":12341232, "price":"210", "sale_price":"209.99"},
{ "item_number":12341233, "price":"20", "sale_price":"12.99"},
{ "item_number":12341234, "price":"150", "sale_price":"19.99"},
{ "item_number":12341235, "price":"60", "sale_price":"29.99"},
{ "item_number":12341236, "price":"10", "sale_price":"5.99"}
];

例如,程序将返回1231234作为特色商品的SKU,因为折扣约为$ 130。

我只想要一个快速的解决方案,不用担心性能。

2 个答案:

答案 0 :(得分:5)

您可以通过一个循环来简化数组,并选择具有最大增量的数组。

var array = [{ item_number: 12341231, price: "250", sale_price: "219.99" }, { item_number: 12341232, price: "210", sale_price: "209.99" }, { item_number: 12341233, price: "20", sale_price: "12.99" }, { item_number: 12341234, price: "150", sale_price: "19.99" }, { item_number: 12341235, price: "60", sale_price: "29.99" }, { item_number: 12341236, price: "10", sale_price: "5.99" }],
    result = array.reduce((a, b) =>
        a.price - a.sale_price > b.price - b.sale_price ? a : b);

console.log(result);

答案 1 :(得分:2)

如果性能不是问题,则可以按降序对产品进行排序,并从排序结果中获取第一个:

const data = [
  { "item_number":12341231, "price":"250", "sale_price":"219.99"},
  { "item_number":12341232, "price":"210", "sale_price":"209.99"},
  { "item_number":12341233, "price":"20", "sale_price":"12.99"},
  { "item_number":12341234, "price":"150", "sale_price":"19.99"},
  { "item_number":12341235, "price":"60", "sale_price":"29.99"},
  { "item_number":12341236, "price":"10", "sale_price":"5.99"}
];

const maxDiffProduct = data.sort((a, b) => (b.price - b.sale_price) - (a.price - a.sale_price))[0];
console.log(maxDiffProduct.item_number);