Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

math.max: find the highest numeric value from a string

How to get the highest numeric value based on indexes like this ?

<div class="repeater-item" data-index="0-0"></div>
<div class="repeater-item" data-index="0-1"></div>
<div class="repeater-item" data-index="0-2"></div>
<div class="repeater-item" data-index="1-0"></div>
<div class="repeater-item" data-index="1-1"></div>
<div class="repeater-item" data-index="2-0"></div>
<div class="repeater-item" data-index="2-1"></div>

In my example, the highest index that must be retrieved is 2-1 in order to increment, thereafter: 1 (2-2, 2,3 ….)

const getIndex = function()
{
    var num = $(".repeater-item").map(function() {
        return $(this).data('index');
    }).get();

    return Math.max.apply(Math, num); // Fail
}

This code fetches the indexes fine but fails to calculate the highest index based on my example

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can for example, sort an array using data-index as a criteria.
Then get first element in the sorted array:

  const getMaxIndex = () => {

    const sorted = $(".repeater-item").sort(function (a, b) {

      const indexANumeric = +$(a).data('index').replace("-", "");
      const indexBNumeric = +$(b).data('index').replace("-", "");

      return indexBNumeric - indexANumeric;

    }).get();

    return $(sorted[0]).data('index');
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading