Мне нужно получить максимальное и минимальное значение массива с несколькими объектами. Я знаю, что в Javascript мы можем использовать для этого Math.min и Math.max в дополнение к другим стратегиям.
Это мое решение работает, но я нахожу код слишком многословным. Можете ли вы сказать мне, как его улучшить?
Заранее большое спасибо.
Вот мой код, который я поместил в codeandbox.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.info(lowest, highest); // return 10, 50
Используйте метод сокращения вместо цикла 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.info(lowest, highest);
Большое спасибо, Рори!! Замечательно
Вы можете начать со значения с нулевого индекса и получить значение напрямую, а не с последнего объекта.
Затем выполните цикл до индекса один.
const
skuStylePlu = [{ skuPrice: { currentPrice: { amount: 10 } } }, { skuPrice: { currentPrice: { amount: 20 } } }, { skuPrice: { currentPrice: { amount: 30 } } }, { skuPrice: { currentPrice: { amount: 40 } } }, { skuPrice: { currentPrice: { amount: 50 } } } ];
let lowest = skuStylePlu[0].skuPrice.currentPrice.amount,
highest = skuStylePlu[0].skuPrice.currentPrice.amount,
i = skuStylePlu.length;
while (--i) {
const value = skuStylePlu[i].skuPrice.currentPrice.amount;
if (value < lowest) lowest = value;
if (value > highest) highest = value;
}
console.info(lowest, highest); // return 10, 50
Вы можете использовать деструктурирование объекта, чтобы немного привести вещи в порядок.
С циклом for:
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;
for(const { skuPrice: { currentPrice: { amount } } } of skuStylePlu) {
lowest = lowest < amount ? lowest : amount;
highest = highest > amount ? highest : amount;
}
console.info(lowest, highest);
Одиночное сокращение для немного большей лаконичности:
const skuStylePlu = [{"skuPrice":{"currentPrice":{"amount":10}}},{"skuPrice":{"currentPrice":{"amount":20}}},{"skuPrice":{"currentPrice":{"amount":30}}},{"skuPrice":{"currentPrice":{"amount":40}}},{"skuPrice":{"currentPrice":{"amount":50}}}];
const [lowest, highest] = skuStylePlu.reduce(
([low, high], { skuPrice: { currentPrice: { amount } } }) =>
[ low < amount ? low : amount, high > amount ? high : amount ],
[Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]
);
console.info(lowest, highest);
Ваш код в порядке, если вы не хотите использовать эти два.