Jump to content

how to apply Math.min on a array who have a null value inside?


espace
 Share

Recommended Posts

Hi, 

I would like to know the lowest value on my array. So i make 

var arr=[0,1,2,3]

console.log(Math.min(...arr)) => 0 ok

The problem is that my array contains this :

var arr=[null,0,2]
var min=Math.min(...arr)
arr.indexOf(min) => -1 because it take null as lowest value...how to eject the null value ?

How do you eject the null value from the Math.min() ?

Edited by espace
Link to comment
Share on other sites

@espace Your code returns the correct "1" for me (Chrome v77 desktop).  Perhaps this is implemented inconsistently across engines?

If so try filtering the array and removing the nulls before the Math.min:

var min=Math.min(...arr.filter(v=>v!=null))

A more optimal solution might be needed if your array is large?

Link to comment
Share on other sites

  • 1 month later...
  • 3 years later...
On 10/22/2019 at 8:58 PM, b10b said:

@espace Your code returns the correct "1" for me (Chrome v77 desktop).  Perhaps this is implemented inconsistently across engines?

If so try filtering the array and removing the nulls before the Math.min:

var min=Math.min(...arr.filter(v=>v!=null))

A more optimal solution might be needed if your array is large?

Better way to do it is using a single for each loop and assign max value by comparing it with each value. That way you don't have to run two loops and in that for each loop you can convert null value to 0 by Number(null). Then compare the value. It is more optimized way of doing things for large arrays.

Example:

Let min = 0;

arr.forEach(item => {

If(Number(item) < min) {

min = Number(item);

}

});

Link to comment
Share on other sites

On 7/22/2023 at 9:45 AM, Pradhumn said:

Better way to do it is using a single for each loop and assign max value by comparing it with each value. That way you don't have to run two loops and in that for each loop you can convert null value to 0 by Number(null). Then compare the value. It is more optimized way of doing things for large arrays.

Example:

Let min = 0;

arr.forEach(item => {

If(Number(item) < min) {

min = Number(item);

}

});

No, not at all.  Perhaps you did not read the question?

The OP's issue (from 2019) was that they wished to exclude nulls in the Math.min response on an array. For example, an array of [null,5,4,3,8] the Math.min would be 0, whereas they intend to see 3.

My solution (from 2019) achieved this by filtering / removing the nulls from the array before the Math.min is encountered.  Whereas yours (from 2023) did not consider the nulls at all (instead it casts them to 0 via Number()) and therefore yields the wrong answer (0, not 3).

Additionally expanding the syntactical sugar (...[]) to a forEach is not necessarily "more optimized" - it may actually be the opposite - the purpose of sugar is to get to the point (from a coding perspective, maintenance perspective, and compiler perspective).  "forEach" is also sugar.  "Optimization" is a different topic entirely and requires benchmarked evaluation and use case strategy.  Additionally your approach introduces temporary variables (let min), evaluates on unecessary items within the array, and double calls casting functions (Number) while turning 1 line of code into 6.

 

Link to comment
Share on other sites

6 hours ago, b10b said:

No, not at all.  Perhaps you did not read the question?

The OP's issue (from 2019) was that they wished to exclude nulls in the Math.min response on an array. For example, an array of [null,5,4,3,8] the Math.min would be 0, whereas they intend to see 3.

My solution (from 2019) achieved this by filtering / removing the nulls from the array before the Math.min is encountered.  Whereas yours (from 2023) did not consider the nulls at all (instead it casts them to 0 via Number()) and therefore yields the wrong answer (0, not 3).

Additionally expanding the syntactical sugar (...[]) to a forEach is not necessarily "more optimized" - it may actually be the opposite - the purpose of sugar is to get to the point (from a coding perspective, maintenance perspective, and compiler perspective).  "forEach" is also sugar.  "Optimization" is a different topic entirely and requires benchmarked evaluation and use case strategy.  Additionally your approach introduces temporary variables (let min), evaluates on unecessary items within the array, and double calls casting functions (Number) while turning 1 line of code into 6.

 

In that case also my solution would be better all we need to do is instead of casting null item to 0 we can just check (item && item < min) in if condition and initial min value to min = Number.MAX_VALUE. Also adding a single min variable will not hurt more than having run loops two times for this thing.

Try to understand the concept here what your solution does is that it runs loop two times to get a single value first to filter the array and then to find min from remaining array. But in my solution you only require to run loop once. I am not using forEach as syntactical sugar, I am just using single loop to filter values and providing us min value. Suppose you have more than a million data which do you think is preferred. Also remember, that when we pass an array to Math.min method it iterate the array also.

I hope you understood the concept now.

Link to comment
Share on other sites

On 7/25/2023 at 4:56 PM, Pradhumn said:

In that case also my solution would be better all we need to do is instead of casting null item to 0 we can just check (item && item < min) in if condition and initial min value to min = Number.MAX_VALUE. Also adding a single min variable will not hurt more than having run loops two times for this thing.

Try to understand the concept here what your solution does is that it runs loop two times to get a single value first to filter the array and then to find min from remaining array. But in my solution you only require to run loop once. I am not using forEach as syntactical sugar, I am just using single loop to filter values and providing us min value. Suppose you have more than a million data which do you think is preferred. Also remember, that when we pass an array to Math.min method it iterate the array also.

I hope you understood the concept now.

Prove it - test whether it is "better".  Run a benchmark.  That is step one of optimization.  Step two is to understand how test data changes, and what may be "better" for one case is not for another.  Remember the OP is an array of 3 items, and their request was to skip the nulls, nothing more - therefore a minimal solution is "better" because it has least impact on their codebase.

Just because code appears to "run loops two times" at syntax level that is not necessarily the case once compiled (as sugar etc may allow a compiler to make optimizations at a deeper level).  A compiler may have cached a dataset already, or have a stored procedure for a common scenario - we do not know by looking at script syntax.  Also the "second loop" is a potentially reduced loop, i.e. it is not necessarily 2*n as you suggest.

Or, if we ignore this and simply take the syntax at face value like you suggest, then your enhanced "solution" introduces >2x more casts and evaluations per (single) loop.  Therefore why do you assume that is "better" than looping twice with 0.5x casts and evaluations?  But don't get distracted by this, it is beside the point.

As I mentioned, optimization is far beyond what can be imagined on first pass, we simply do not know what the optimal solution is in the wild because every case is different and only tests reveal reality.  What we can do is make readable, reusable code that is optimal to write and maintain.  I follow this approach because it lets Programmers code with expression (timeless), and allows Compilers to seek efficiency (progressive).

Link to comment
Share on other sites

  • 3 months later...

To find the minimum value in an array that contains null values and you want to exclude them from the calculation, you can filter out the null values before applying Math.min(). Here's a solution in JavaScript:
 

var arr = [null, 0, 2];

// Use filter to exclude null values
var filteredArr = arr.filter(value => value !== null);

if (filteredArr.length > 0) {
  // If there are non-null values in the filtered array, find the minimum
  var min = Math.min(...filteredArr);
  console.log(min); // This will output the minimum value
} else {
  // Handle the case when all values were null
  console.log("Array contains only null values");
}

This code first filters out the null values from the array, and then it applies Math.min() to find the minimum value from the remaining non-null values. Resource- 

Linux administration certification and developer.mozilla.org  

I hope this will help you.

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...