The problem is, when applying Math.min
to the result of mapping the original array to the prices and delivery times, you lose the reference to the desired object. In this situation, although you have the value the lowest price and the lowest delivery time, you have no reference to the object to which they now belonged.
Therefore, you should look for a way to keep reference to objects. For this, you can use a for
to iterate over each object, creating two objects (external to the for
) to store which is the least priced item and the least delivery time item.
As the loop is iterating, you check whether the current meets the criteria better than the previous one and, if positive, changes the "reference object".
Something like that:
const response = [
{ id: 1, price: 10, available: true, delivery_time: 20 },
{ id: 2, price: 10, available: true, delivery_time: 7 },
{ id: 3, price: 30, available: true, delivery_time: 5 },
{ id: 4, price: 40, available: true, delivery_time: 1 }
];
let minPrice = response[0];
let minDeliveryTime = response[0];
// Como já começamos no primeiro elemento da lista, podemos começar a iterar
// a partir do segundo (índice 1):
for (let i = 1; i < response.length; i++) {
const current = response[i];
// Se o preço for menor que o atual, substituimos:
if (current.price < minPrice.price) {
minPrice = current;
}
// Se o tempo de entrega for menor que o atual, substituimos:
if (current.delivery_time < minDeliveryTime.delivery_time) {
minDeliveryTime = current;
}
}
console.log(minPrice);
console.log(minDeliveryTime);
Probably have to encapsulate this in a relatively generic function, but I leave as a challenge. If you have time, I add here later. :-)
Wow, thank you so much for the help. I will seek to solve this challenge kk
– user188589
You are welcome, @VHB. See on [tour] how to thank here. You can accept the answer and vote positive if you feel it is relevant. :)
– Luiz Felipe