The map function in Math.min returns NaN when there is a 0 in the collection

I'm currently troubleshooting a code snippet that involves determining the minimum and maximum values within a collection. Everything was functioning well until I added 0 values to the collection, which caused the function to return NaN. The function works as expected when run without any 0 values.

const minVal = Math.min(...this.wells.map(d => Number(d.valueText) || Number(d.value)));
const maxVal = Math.max(...this.wells.map(d => Number(d.valueText) || Number(d.value)));

For instance, if we have values ranging from 2 to 0.00003 to 0, the minimum value should be 0 and the maximum value should be 2.

If the values were from 10 to 0.000000001 or from 1 to 10000, the function would work correctly.

let wells = [];

wells.push({
  posCol: 0,
  posRow: 0,
  valueText: 2
});
wells.push({
  posCol: 1,
  posRow: 0,
  valueText: 4
});
wells.push({
  posCol: 2,
  posRow: 0,
  valueText: 0
});

const minVal = Math.min(...wells.map(d => Number(d.valueText) || Number(d.value)));
const maxVal = Math.max(...wells.map(d => Number(d.valueText) || Number(d.value));

console.log(minVal);
console.log(maxVal);

Below is an example of working code:

let wells = [];

    wells.push({
      posCol: 0,
      posRow: 0,
      valueText: 2
    });
    wells.push({
      posCol: 1,
      posRow: 0,
      valueText: 4
    });
    wells.push({
      posCol: 2,
      posRow: 0,
      valueText: 1
    });

    const minVal = Math.min(...wells.map(d => Number(d.valueText) || Number(d.value)));
    const maxVal = Math.max(...wells.map(d => Number(d.valueText) || Number(d.value)));

    console.log(minVal);
    console.log(maxVal);

SOLUTION FOR ANYONE ENCOUNTERING THIS ISSUE (See @VLAZ Explanation)

    let wells = [];

    wells.push({
      posCol: 0,
      posRow: 0,
      valueText: 2
    });
    wells.push({
      posCol: 1,
      posRow: 0,
      valueText: 4
    });
    wells.push({
      posCol: 2,
      posRow: 0,
      valueText: 0
    });

    const minVal = Math.min(...wells.map(d => Number(d.value) || Number(d.valueText)));
    const maxVal = Math.max(...wells.map(d => Number(d.value) || Number(d.valueText)));

    console.log(minVal);
    console.log(maxVal);

The issue arose from the fact that the value 0 was being evaluated as falsy, causing the function to default to an undefined property, resulting in NaN. The solution involved swapping the positions of the two number checks.

Answer №1

RESOLUTION FOR ANYONE ENCOUNTERING THIS PROBLEM Reference @VLAZ Explanation

    let wells = [];

    wells.push({
      posCol: 0,
      posRow: 0,
      valueText: 2
    });
    wells.push({
      posCol: 1,
      posRow: 0,
      valueText: 4
    });
    wells.push({
      posCol: 2,
      posRow: 0,
      valueText: 0
    });

    const minVal = Math.min(...wells.map(d => Number(d.value) || Number(d.valueText)));
    const maxVal = Math.max(...wells.map(d => Number(d.value) || Number(d.valueText)));

    console.log(minVal);
    console.log(maxVal);

The problem stemmed from the fact that a value of 0 was treated as falsy, leading to a fallback scenario resulting in an undefined property and ultimately NaN. The solution involved rearranging the order of operations.

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

Is it possible to set up a universal type definition in TypeScript version 2 and above?

I have a collection of straightforward .ts files, not part of any projects but standalone .ts scripts. They implement certain node.js features. Both TypeScript and node type definitions are set up through the following commands: npm install -g typescript ...

Leveraging the Jira REST API and JSON to generate a Test Issue complete with specific test details

I've successfully created the Test issue, but I'm having trouble finding the correct JSON structure to populate the field: customfield_11101, name: Zephyr Teststep, required: false, type: any My desired format is something like this: var issueT ...

Unraveling nested JSON in C#

I'm currently attempting to convert an XML response from a rest API into a JSON string. My goal is to deserialize the JSON and use it as a strongly typed object in C#. While I have made some progress, I am encountering difficulties along the way. The ...

Exploring in Angular 2 by using First Name, Last Name, and Email for queries

Details Currently, I am working on implementing a search functionality using pipes. Users should be able to search by email, first name, or last name. At the moment, it only works for searching by email. I am looking to extend this capability so that user ...

Using Ruby on the command line to beautify JSON data

I've utilized Python in the past to create visually appealing output of JSON data, using this command: python -mjson.tool input.json Now, I'm attempting to achieve a similar result with Ruby. Currently, I'm using the following command: ru ...

Angular causes the website to become unresponsive following certain animations

I am experiencing an issue with my Angular website where I have implemented an effect to show and hide photos on the homepage. The problem arises when after a certain period of time, the Chrome browser crashes and the website freezes. It seems like the con ...

Ensure that the key of an object's property is identical to the value of the property

I am tasked with creating a specific object structure, where each object key must match its corresponding ID: const entities = { abc: { id: 'abc' }, def: { id: 'def' } } To achieve this, I attempted the following code: ...

Fashion for the repetitive elements, activated by events

Looking for ways to style a specific table element that is generated from a repeat.for loop on a <td> tag. <td repeat.for="field of fields" class="${field.fieldKey == 'validTo' ? 'fontweigth: bold;': ''}"> b ...

I am facing an issue where the data is not being populated in my form even though I am using ng

Here is a form with grouped inputs using the ngModelGroup directive: <form #form="ngForm" (ngSubmit)="submit(form.value)"> <fieldset ngModelGroup="user"> <div> <label>Firstname:</label> < ...

Rails gives a response of HTML when angular sends a resource.get request

Having trouble with Rails 4 responding to an angular resource.get request with HTML instead of JSON. The code snippet for the javascript is as follows: $resource("/questions/:id", {id: "@id"}}.get({id: 16}); The server error occurs because it cannot loc ...

Browser Add-On for Google Chrome

I have several inquiries that require responses. I am in the process of developing a Google Chrome extension and need to monitor every page for keyboard actions. I have implemented a content script that runs when the page loads and displays an alert when y ...

What could be causing the reliability issue with this particular Angular JS code for dropdown menus?

Attempting to create a dynamic country-city dropdown menu using AngularJS <div> Country: </br> <select data-ng-model="country" ng-options="country.name for country in countries" data-ng-change="updateCountry(country) ...

Leveraging Jackson2 in Spring 4.0 (featuring MVC, REST, and Hibernate integration)

I am working on a project to create a RESTful application and need to convert a list of objects into JSON for a specific URL using @RequestMapping / @ResponseBody annotations. Currently, I have jackson-hibernate4, jackson-core, databind, etc., in my class ...

An issue arises when utilizing a string variable in React-bootstrap's OverlayTrigger placement attribute

I encountered an unexpected issue with the OverlayTrigger component in React-Bootstrap version 5.1.1. I'm attempting to develop a custom button component using OverlayTrigger and a standard button. Everything is functioning as intended, except for whe ...

"Issues with passing a model in an Ajax post request on an Aps.net Core Razor page causing it

When working with Asp.Net core, I encountered an issue where my razor page was not properly sending an Ajax post to a Post method as the model always returned null. Here is a simplified version of my question: public class IndexModel : PageModel { pub ...

How can we transfer or exclude all boolean properties from one class to another or a "type"?

Within my Nestjs application, there is an entity class structured like this: @ObjectType() export class Companies { @Field(() => Int) @PrimaryGeneratedColumn({ type: 'int', name: 'id' }) public id: number; @Field() @Column ...

What is the best way to parse and extract multiple objects from a JSON stream?

Hey there, I've sought help on similar topics before, but this time it's a new problem that I thought warranted its own discussion. Apologies if this is not the correct approach... So here's the deal: Currently, I'm working on parsing ...

Having trouble connecting JSON data to TreeTable Js through knockout.js?

I found a helpful plugin called TreeTable that I am using. You can check it out here: <table id="example-basic"> <thead> <tr> <th>Name</th> <th>Status</th> <th>id</th> ...

Is it possible to utilize pinia getter as the initial parameter in Vue3's watch function?

Issue Recap In Vue3, can Pinia getters be utilized as a watch target's first argument? System Details Vue version: 3.2.13 Pinia version: 2.1.4 TypeScript version: 4.5.5 Problem Description An error was encountered when attempting to reference the ...

Proven method for transforming an Object containing a Map into a JSON Object

Is there a way to convert an object containing a map to JSON without losing the map data? When I use JSON.stringify(), the map data gets cleared. How can I solve this issue? frieghtChargesJSon:string; //declared variable frieghtChargesJSon=JSON.stringify ...