I have a sorted array is
array = [
{ id: 1, orderTotal: 50000 },
{ id: 3, orderTotal: 50000 },
{ id: 2, orderTotal: 100000 },
{ id: 4, orderTotal: 200000 },
]
I want find all order total if nearest with a total price.
This is my code
const getNearestOrderValue = (arr, totalPrice) => {
let nearestItem = [];
let maxSmaller = 0;
for (const item of arr) {
if (item?.orderTotal <= totalPrice && item?.orderTotal >= maxSmaller) {
maxSmaller = item?.orderTotal;
nearestItem.push(item);
}
}
return nearestItem;
}
if total price = 80000, my code return correct result is
[
{ id: 1, orderTotal: 50000 },
{ id: 3, orderTotal: 50000 },
]
but if total price is 120000, my code result is
[
{ id: 1, orderTotal: 50000 },
{ id: 3, orderTotal: 50000 },
{ id: 2, orderTotal: 100000 }
]
I want result is
[
{ id: 2, orderTotal: 100000 }
]
How can i fix this getNearestOrderValue function to response correct? I am looking forward to receive help from anyone.
4
Answers
You can loop twice. Once to find the
maxSmaller
item and then to filter the original array:You just have to reset your output array when you find a closer value. There is no need to loop 2*n times and definitely no need to loop n^2 times.
As noted by Nick Parsons in the comments, you can even break out of the loop once you encounter an
orderTotal
that is greater than thetotalPrice
.You could reduce the array and keep only items with smaller total values.
Check this out it will resolve your problem.