Search code examples
arraysfor-loopnumbersmax

Get Max number from array


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

Solution

  • 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>