Home > Enterprise >  Get Max number from array
Get Max number from array

Time:12-18

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  id="element-2" ><div>
<div  id="element-58" ><div>
<div  id="element-135" ><div>
<div  id="element-39" ><div>
<div  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));

CodePudding user response:

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  id="element-2">
</div>
<div  id="element-58">
</div>
<div  id="element-135">
</div>
<div  id="element-39">
</div>
<div  id="element-78">
</div>

  • Related