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));
1 Answer 1
You can add the id
s 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
-
You must have tested the answer before I edit it. Please try the current answer, it should work correctlydreambold– dreambold12/18/2022 09:17:43Commented Dec 18, 2022 at 9:17
-
1I tested before you edited, now it works.sanels– sanels12/18/2022 09:22:55Commented Dec 18, 2022 at 9:22
-
Is this the only and most correct approach? Could you please explain why?sanels– sanels12/18/2022 09:24:20Commented 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>
dreambold– dreambold12/18/2022 09:25:54Commented 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?sanels– sanels12/18/2022 09:30:58Commented Dec 18, 2022 at 9:30