Question:
How to Filter all item with lowest nearest value in array using javascript?

To Filter all item with lowest nearest value in array using javascript, you just have to reset your output array when you find a closer value. 


Also, 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) {

          break;

        } else if (item?.orderTotal >= maxSmaller) {

          if (item?.orderTotal > maxSmaller) {

            maxSmaller = item?.orderTotal;

            nearestItem = [];

          }

          nearestItem.push(item);

        }

    }

    return nearestItem;

}


console.log(getNearestOrderValue(array, 50000));

console.log(getNearestOrderValue(array, 120000));


Read more:

>How to allign two plots in Matplotlib?


Answered by: >Robby Cornelissen

Credit:> Stack Overflow


Suggested blogs:

>How to migrate `DateTimeField` to `DateField` in Django?

>Why VSCode indicate an error on using {{ }}?

>Fix the python-decouple issue in Django

>Address the N+1 problem in Django with prefetch

>Know everything about AWS Resource Explorer: Full Guide

>Reasons why you cannot ping your AWS EC2 instance: How to fix it

>AWS API Gateway: Ways to do REST API Versioning

>4 easy ways to select an AWS Profile when using Boto3 to connect to CloudFront

>How to use Wildcards to ‘cp’ a File Group with AWS CLI

>AWS EFS vs EBS vs S3: What are the best AWS storage options



Submit
0 Answers

What Our Clients Say About Us

Client satisfaction is our ultimate goal. Here are some kind words of our precious clients they have used to express their satisfaction with our service.

Why Choose Us ?

We endow businesses with flexible engagement models based on their unique needs. Our strength lies in state-of-the-art technology and affordable consulting services. Try us for fast POCs, full-fledged applications, or technology consulting. Always available for your service.