Discover the lowest value within an array of objects while applying specific conditions

    let event = [
    {
        "vendorBidId": 58,
        "participantName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d7c7da9bd2d0d0f5c1d0c6c19bdcdb">[email protected]</a>",
        "bidAmount": 10000,
        "productionRate": 10000,
        "bidTime": "2021-10-21T14:55:05.957324",
        "isYou": false,
        "awarded": false
    },
    {
        "vendorBidId": 57,
        "participantName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8efaebfdfacee9e3efe7e2a0ede1e3">[email protected]</a>",
        "bidAmount": 20000,
        "productionRate": 20000,
        "bidTime": "2021-10-21T14:50:24.493522",
        "isYou": false,
        "awarded": true
    },
    {
        "vendorBidId": null,
        "participantName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81e3f3eeaab3c1f5e4f2f5afe2eeec">[email protected]</a>",
        "bidAmount": 0,
        "productionRate": null,
        "bidTime": null,
        "isYou": false,
        "awarded": false
    },
    {
        "vendorBidId": null,
        "participantName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e0f0edaceae7fbc2f6e7f1f6ace1edef">[email protected]</a>",
        "bidAmount": 0,
        "productionRate": null,
        "bidTime": null,
        "isYou": true,
        "awarded": false
    }
]

I am seeking to identify the lowest bid amount with the following condition in place:

  1. Skip over any entries with a null value for vendorBidId.

This is my attempt at achieving this:

let minimum = event.reduce(function(prev, curr) {
    if (curr.vendorBidId !== null) {
        return prev.bidAmount < curr.bidAmount ? prev : curr;
    }
    return prev;
});

However, I encountered challenges when incorporating my specific requirement into the code.

I only wish to determine the minimum bid amount while disregarding entries where vendorBidId is null.

Answer №1

Using Math.min with Filter and Map Functions

let event = [{ "vendorBidId": 58, "participantName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa988895d49d9f9fba8e9f898ed49394">[email protected]</a>", "bidAmount": 10000, "productionRate": 10000, "bidTime": "2021-10-21T14:55:05.957324", "isYou": false, "awarded": false }, { "vendorBidId": 57, "participantName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9febfaecebdff8f2fef6f3b1fcf0f2">[email protected]</a>", "bidAmount": 20000, "productionRate": 20000, "bidTime": "2021-10-21T14:50:24.493522", "isYou": false, "awarded": true }, { "vendorBidId": null, "participantName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472535286c7507332234336924282a">[email protected]</a>", "bidAmount": 0, "productionRate": null, "bidTime": null, "isYou": false, "awarded": false }, { "vendorBidId": null, "participantName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d7c7da9bddd0ccf5c1d0c6c19bd6dad8">[email protected]</a>", "bidAmount": 0, "productionRate": null, "bidTime": null, "isYou": true, "awarded": false } ]

const min = Math.min(...event
  .filter(evt => evt.vendorBidId)
  .map(({bidAmount}) => bidAmount)
);  

console.log(min)

Answer №2

When it comes to getting the entire object, using reduce is a straightforward method.

For just finding the minimum value, you can employ Math.min by first mapping the key values of minAmount.

  let event = [
    {
        "vendorBidId": 58,
        "participantName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e183938ecf868484a195849295cf888f">[email protected]</a>",
        "bidAmount": 10000,
        "productionRate": 10000,
        "bidTime": "2021-10-21T14:55:05.957324",
        "isYou": false,
        "awarded": false
    },
    {
        "vendorBidId": 57,
        "participantName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f5e4f2f5c1e6ece0e8edafe2eeec">[email protected]</a>",
        "bidAmount": 20000,
        "productionRate": 20000,
        "bidTime": "2021-10-21T14:50:24.493522",
        "isYou": false,
        "awarded": true
    },
    {
        "vendorBidId": null,
        "participantName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f2d3d20647d0f3b2a3c3b612c2022">[email protected]</a>",
        "bidAmount": 0,
        "productionRate": null,
        "bidTime": null,
        "isYou": false,
        "awarded": false
    },
    {
        "vendorBidId": null,
        "participantName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8cadac786c0cdd1e8dccddbdc86cbc7c5">[email protected]</a>",
        "bidAmount": 0,
        "productionRate": null,
        "bidTime": null,
        "isYou": true,
        "awarded": false
    }
]

const min = event.reduce(function(prev, curr) {
    return prev.bidAmount < curr.bidAmount && curr.vendorBidId ? prev : curr;
});

console.log(min);

var minValue = Math.min(...event.map(item => item.vendorBidId ?   item.bidAmount : 0));

console.log(minValue);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing a Generic API Invocation Function

I'm currently working on a function that has the capability to call multiple APIs while providing strong typing for each parameter: api - which represents the name of the API, route - the specific route within the 'api', and params - a JSON ...

Are there any functions that work with an array of objects?

Is there a way to use includes function to check if an object is inside the array, as shown below: arr=[{name:'Dan',id:2}] When trying to check with includes like this: arr.includes({name:'Dan',id:2}) The result returned is false. I ...

What is the process for obtaining a push key in Firebase?

When a user submits data to the Firebase database, I need to handle the Key generated by that action in my own function. The challenge arises when a user fills out a form and sends data to our real-time DB. This data may include optional images, and I wan ...

What is the best way to add a refresh link to my CAPTCHA script?

I have a captcha script that is functioning well. However, I am struggling to figure out how to implement a refresh function for it. Below is the code from verificationimage.php: <?php header('Content-type: image/jpeg'); $width = 50; $heig ...

Find the height of the viewport using jQuery, subtracting (n) pixels

Apologies if the topic seems puzzling, I couldn't find a better way to explain it. I utilized jQuery to adjust the height of a div to match the size of the viewport. var slidevh = function() { var bheight = $(window).height(); $(".container" ...

What could be causing the onClick event handler to trigger twice in my create-react-app?

Does anyone know why the "upvote" onClick handler is triggering twice? Even though the logs show it's only running once, the score increases by 2 export default class Container extends Component { constructor(props) { super(props); this.sta ...

Unable to dynamically update textbox with dropdown value in Internet Explorer [Using JavaScript]

I am attempting to modify the text in a textbox when a choice is made from a dropdown form element using the onchange() function. While this process works smoothly in Firefox, Safari, and Chrome, it fails to do so in Internet Explorer. Below is the simpl ...

Updating Error: Unable to establish connection with IP address 104.16.21.35 on port 80; Error code: ECONNREFUSED. This issue is being handled by the _

I need help updating my Angular version from 5 to 6 and I'm following these steps: Want to upgrade project from Angular v5 to Angular v6 After running the commands ng update @angular/cli and ng update @angular/core, I encountered the err ...

Prevent repeating the same table header multiple times when generated dynamically with jQuery

I have an array called groups which contains name and regid. I want to display the name key as the column header of a table. To achieve this, I implemented the following code: var Name = v.name; var regId = v.regid; var rowStr = '<th d ...

The JSON data appears to be correct, yet it is not functioning properly when transmitted to X

I have a JSON object that has been validated using https://jsonlint.com/. However, I am encountering an error when trying to use this JSON with the Xero API as shown below. { "Type": "ACCREC", "Status": "AUTHORISED", "DueDate": "2021-12-11T14:24:0 ...

Is there a way to enable multiple selections in a particular section?

Currently, I am in the process of working on my step by step order and I want to express my gratitude for all the assistance I have received so far. Despite the help, I still have some unanswered questions! The steps in my project are categorized into dif ...

When it comes to deploying middleware, accessing cookies becomes more challenging. However, in a local setup, Next.js allows middleware to

I have set up a NextJS frontend application with a backend powered by NodeJS and ExpressJS. Authentication and authorization are handled using JWT token-based system, where the backend server sets the token and the frontend server validates it to grant acc ...

How to prevent page refresh when hitting enter in jQuery form?

Currently, my form does not refresh the page when I click the button to submit it. However, if I press Enter while a text input is selected, the page will refresh. Is there a way to make pressing Enter on the text input perform the same action as clicking ...

Limit the selected values to calculate a partial sum

Imagine two distinct classes called professor and student: professor.ts export class Professor { id: number name: string } student.ts import { Professor } from "./professor" export class Student { ...

Efficient communication in Angular: Sharing data among controllers and components

Recently joining a new project, I am faced with the task of implementing a small feature. In my setup, there are 2 distinct views: Cars.html and Wheels.html The Cars.html view is associated with the controller Cars.controller.js On the other hand, the W ...

How can you set up an event listener for multiple keys in a React application

I'm trying to implement an event listener that detects when the command+c keys are pressed to copy something to the clipboard. However, I want to listen for multiple keys at once. I attempted to use useState, useEffect, and document.addEventListener, ...

`How can I utilize typeahead.js to easily read JSON data?`

Looking to utilize JSON file data with typeahead.js for your project? Check out this link. With typeahead.js, users can input a word like "EnglishWords [Best]" and receive a list of all words similar to or starting with "best". Upon selection, the descrip ...

Creating a Map Using HTML and JavaScript

My current project involves creating a simple map that can be moved with mouse drag functionality, featuring images such as islands. I have successfully retrieved the mouse position by declaring variables posX and e.clientX, as well as for e.clientY. Howe ...

Modifying the chart width in Chart.js: A step-by-step guide

After creating a chart using Chart Js, I encountered an issue where the chart did not fit within the specified width. Adjusting the attributes of canvas proved to be ineffective, specifically with regards to the width attribute. Despite changing the value, ...

Arrangement of pipe operators in RXJS Angular 5

Do you think my operators are in the correct order? The code snippet below shows that the console logs from the two taps display the same values. Something seems off, right? return this.pcs.getAvailableMaterials(currentProduct.id).pipe( map( ...