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.
>Solution :
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.
const array = [
{ id: 1, orderTotal: 50000 },
{ id: 3, orderTotal: 50000 },
{ id: 2, orderTotal: 100000 },
{ id: 4, orderTotal: 200000 },
];
const getNearestOrderValue = (arr, totalPrice) => {
let nearestItem = [];
let maxSmaller = 0;
for (const item of arr) {
if (item?.orderTotal <= totalPrice && item?.orderTotal >= maxSmaller) {
if (item?.orderTotal > maxSmaller) {
maxSmaller = item?.orderTotal;
nearestItem = [];
}
nearestItem.push(item);
}
}
return nearestItem;
}
console.log(getNearestOrderValue(array, 120000));