Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter all item with lowest nearest value in array using javascript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading