javascript - 如何在javascript中获取对象数组中的最大值和最小值?

标签 javascript data-structures reduce

我需要获取包含多个对象的数组的最大值和最小值。我知道在 Javascript 中,除了其他策略之外,我们还可以使用 Math.minMath.max 来实现此目的。

我的这个解决方案有效,但我发现代码太冗长了。你能告诉我如何改进吗?

提前非常感谢您。

这是我放入 codesandbox.io 的代码

const skuStylePlu = [{
    skuPrice: {
      currentPrice: {
        amount: 10
      }
    }
  },
  {
    skuPrice: {
      currentPrice: {
        amount: 20
      }
    }
  },
  {
    skuPrice: {
      currentPrice: {
        amount: 30
      }
    }
  },
  {
    skuPrice: {
      currentPrice: {
        amount: 40
      }
    }
  },
  {
    skuPrice: {
      currentPrice: {
        amount: 50
      }
    }
  }
];

let lowest = Number.POSITIVE_INFINITY;
let highest = Number.NEGATIVE_INFINITY;
let temp;

for (let i = skuStylePlu.length - 1; i >= 0; i--) {
  temp = skuStylePlu[i].skuPrice.currentPrice;

  if (temp.amount < lowest) {
    lowest = temp.amount;
  }
  if (temp.amount > highest) {
    highest = temp.amount;
  }
}

console.log(lowest, highest); // return 10, 50

最佳答案

使用reduce方法而不是for循环。

const skuStylePlu = [{
    skuPrice: {
      currentPrice: {
        amount: 10
      }
    }
  },
  {
    skuPrice: {
      currentPrice: {
        amount: 20
      }
    }
  },
  {
    skuPrice: {
      currentPrice: {
        amount: 30
      }
    }
  },
  {
    skuPrice: {
      currentPrice: {
        amount: 40
      }
    }
  },
  {
    skuPrice: {
      currentPrice: {
        amount: 50
      }
    }
  }
];
const prices = skuStylePlu.map(obj => obj.skuPrice.currentPrice.amount);
const lowest = prices.reduce((acc, curr) => Math.min(acc, curr), Number.POSITIVE_INFINITY);
const highest = prices.reduce((acc, curr) => Math.max(acc, curr), Number.NEGATIVE_INFINITY);
console.log(lowest, highest);

关于javascript - 如何在javascript中获取对象数组中的最大值和最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75463015/

相关文章:

java - 如何创建一个树状结构,其中有不同类型的节点,并且每个节点可以引用任何节点?

c++ - 2-prop 排序列表的正确数据结构是什么?

javascript - 在 JavaScript 中循环数组时忽略空字符串

hadoop - hive 中的 reducer 选择

javascript - Meteor.call 即使有回调函数也会引发异常

javascript - 文件对象未定义 NuxtJS AsyncData()

javascript - 选中与输入字段同一行的复选框

javascript - jQuery - 按 id 按降序排列元素的按钮

algorithm - 在大量 URL 中检测重复网页

javascript - 使用 Ramda 将 reducer 转换为传感器