espace

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

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

Share this post


Link to post
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?

Share this post


Link to post
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...

  • Recently Browsing   0 members

    No registered users viewing this page.