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));
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>

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

8 Comments

You must have tested the answer before I edit it. Please try the current answer, it should work correctly
I tested before you edited, now it works.
Is this the only and most correct approach? Could you please explain why?
What else do you need? It's a correct answer, and your HTML code was wrong, without closing div tags, </div>
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?
|

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.