我需要获取包含多个对象的数组的最大值和最小值。我知道在 Javascript 中,除了其他策略之外,我们还可以使用 Math.min
和 Math.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/