cancel
Showing results for 
Search instead for 
Did you mean: 

How to get max element of array and its corresponding index

vaidyarm
Contributor

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 2

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:
image

Output:
image

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

Thanks for input!!