Forum Discussion

vaidyarm's avatar
vaidyarm
Contributor
4 years ago

How to get max element of array and its corresponding index

How can we get the max element of the array with its corresponding index?

Ex : “somefield” : [1,2,2,2,2,1,1,1,1]

Max element is 2 and indexes are 1,2,3,4

2 Replies

  • bojanvelevski's avatar
    bojanvelevski
    Valued Contributor

    Hey @vaidyarm,

    Use the following expression in a mapper to get the expected result:

    $array.map((x,index)=>{"value":x,"index":index}).filter(x=>x.value==($array.sort((a,b)=>b-a)[0]))

    This will produce an array of objects, which will contain the max value, and It’s corresponding index.

    Input:

    Output:

    • vaidyarm's avatar
      vaidyarm
      Contributor

      Hey, did the similar, but keeping the filter in one mapper and sort as snap.

      Thanks for input!!