-1

I have an below array with elements.

Array [
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  4116.38,
  4120.87,
  0,
  0,
  0,
]

How can i filter all the "0" value and the maximum value from the array?

  • 2
    You don't, you just use `const maxInYourArray = Math.max(...yourarray)`, relying on [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax), because the [max function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Math/max) can take an arbitrary number of values as function arguments. – Mike 'Pomax' Kamermans Oct 12 '21 at 05:00
  • If you want array without `0` then use `arr.filter(n => n)`, – DecPK Oct 12 '21 at 05:01
  • @svarog note that that answer is bogged down with decades of legacy code. The modern JS solution isn't even a one-liner. Trying to sift through all the answers on that post is a non-starter for anyone looking for how to do this today. – Mike 'Pomax' Kamermans Oct 12 '21 at 05:04
  • what legacy code? some of the answers are from last year – svarog Oct 12 '21 at 05:05
  • yes, if you wade through the literally three pages of answers. That makes it a post with too much baggage to give anyone a good, solid, immediate answer that is applicable today. – Mike 'Pomax' Kamermans Oct 12 '21 at 05:06
  • @Mike'Pomax'Kamermans That consideration is rather irrelevant when it comes to question duplication. Users are free to sort the pages of answers in several ways. To your point, we don't need duplicate answers leaking out into 53 other posts, repeat ad nauseam. – Drew Reese Oct 12 '21 at 05:11
  • 1
    flagging a post for duplication serves the same purpose as answering: helping people (both this user, and all future users who find this post) get answers, not setting them to task. A question with 53 answers covering over a decade of JS does not serve that purpose. – Mike 'Pomax' Kamermans Oct 12 '21 at 05:13

1 Answers1

0

You don't, you just use const maxInYourArray = Math.max(...yourArray), relying on modern spread syntax to turn your array into distinct arguments, because the Math.max function can take an arbitrary number of values as function arguments and returns the maximum value amongst them.

The same applies to Math.min, but that will obviously give you 0, so if you want to ignore all those zeroes, filter them out first: const minInYourArray = Math.min(...yourArray.filter(v => v!==0))

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153