1

I need to take the id from each element and isolate the number. After that, create an array of numbers and get the largest number. In Math.max() I get NaN. Is this a good or bad approach and why am I not getting the highest number?

<div class="element" id="element-2" ><div>
<div class="element" id="element-58" ><div>
<div class="element" id="element-135" ><div>
<div class="element" id="element-39" ><div>
<div class="element" id="element-78" ><div>
 var element_numbers = document.getElementsByClassName("element");
 var max_comm = "";
 for (var i = 0; i < element_numbers.length; i++) {
 var num = element_numbers[i].id;
 const num_arr = num.match(/[0-9]+$/);
 max_comm += num_arr+",";
 } 
 var max_num = "["+max_comm.slice (0, -1)+"]";
 alert(max_num);
 alert(Math.max(max_num));
asked Dec 18, 2022 at 8:36
0

1 Answer 1

1

You can add the ids to an array and use the sort() function to sort the array elements and the first element of the returned array is the max value. So the code will look like:

 var element_numbers = document.getElementsByClassName("element");
var max_comm = [];
for (var i = 0; i < element_numbers.length; i++) {
 var num = element_numbers[i].id;
 const num_arr = num.match(/[0-9]+$/);
 max_comm.push(parseInt(num_arr));
} 
console.log(max_comm.sort((a, b) =>( b - a)));
alert(Math.max(...max_comm));
 
<div class="element" id="element-2">
</div>
<div class="element" id="element-58">
</div>
<div class="element" id="element-135">
</div>
<div class="element" id="element-39">
</div>
<div class="element" id="element-78">
</div>

answered Dec 18, 2022 at 8:58
8
  • You must have tested the answer before I edit it. Please try the current answer, it should work correctly Commented Dec 18, 2022 at 9:17
  • 1
    I tested before you edited, now it works. Commented Dec 18, 2022 at 9:22
  • Is this the only and most correct approach? Could you please explain why? Commented Dec 18, 2022 at 9:24
  • What else do you need? It's a correct answer, and your HTML code was wrong, without closing div tags, </div> Commented Dec 18, 2022 at 9:25
  • Everything is fine, I put your answer as correct..., the only thing I'm asking is if this is the only approach, why it didn't work with math.max? Commented Dec 18, 2022 at 9:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.