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

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

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

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


    return $(sorted[0]).data('index');

Leave a Reply