-3

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

Raphael M
  • 15
  • 2
  • You're trying to perform math on *strings*, not *numbers*. Do you just want to sort the values in descending alphanumeric order and return the first resulting element? – David Apr 19 '23 at 11:17
  • The linked duplicate demonstrates how to sort your strings in descending order. Once sorted, you can just grab the first element from the resulting array. – David Apr 19 '23 at 11:26

1 Answers1

0

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');
  }
munleashed
  • 1,677
  • 1
  • 3
  • 9