0

Having a little bit of trouble with Math.max.apply(); seem to be able to get the result I want to show within a console.log(); but when adding it to a variable and console loggin that it just throws a -Infinity message within the console.

The idea is to grab all the numbers from the .onsale classes then add to a variable and work out the max number from those, then inject that max number into an element on the page but got stuck trying to calculate the largest number from an array and add it to a variable in this case savingMax. Have I gone down the wrong path?

Here is my code so far.

<div class="onsale">79</div>
<div class="onsale">91</div>
<div class="onsale">20</div>
jQuery(document).ready(function($){

  var savingArray = [];

  var savingMax; //Example variable for holding the highest number ready for inserting in DOM

  $(".onsale").each(function (){

    var saving = $(this).text();
    var savingAmount = saving.replace(/\D+/g, '');
    savingArray.push(savingAmount);

  });

  console.log(Math.max.apply(Math, savingArray));

});

The document ready is needed on my theme I am apply the code on. Jsfiddle Example

1 Answer 1

1

It seems working fine. I've assigned max value to savingMax variable and displaying it then printing it using console.

Array size is the one reason I can think of for this issue. But I hope in your case it is less than 1K.

$(document).ready(function($){

  var savingArray = [];

  $(".onsale").each(function (){
    var saving = $(this).text();
    var savingAmount = saving.replace(/\D+/g, '');
    savingArray.push(savingAmount);

  });
  
  var savingMax = Math.max.apply(Math, savingArray);
  // Displaying it
  $('#saving-max').text('Saving Max=' + savingMax);
  
  // Printing using console
  console.log('savingMax=', savingMax);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="onsale">79</div>
<div class="onsale">91</div>
<div class="onsale">20</div>

<div id="saving-max"></div>

Reference

Math.max()

Using apply and built-in functions

Sign up to request clarification or add additional context in comments.

5 Comments

Try this and let me know if you need some help.
Thats perfect, thanks very much. You couldnt explain to me why I was getting the -infinity error when I tried adding it into a variable then calling that via console log?
I'm just curious, tell the max array size that one can expect? Cause generally if it is a large number, you'll face this issue.
The numbers will be between 1 and 100 but the numbers on the page will change so needed to get what ever numbers are there and just find the highest.
Then it is fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.