简体   繁体   中英

How can I find the index of the greatest value in an array then target and return a different value with the same index

I have a JSON payload shown below. I want to loop through and find the one with the highest value for "numUsed". Then, I want to display that number along with the associated "type". For the example below, I'd like to end up with:

"Your favourite benefit was Benefit C, you used it 18 times!"

In its final state, I'd like to disregard the "All Benefits" section.

"Benefits": [
                        {
                            "type": "Benefit A",
                            "dollarSavings": 0,
                            "timeSavings": 0,
                            "numUsed": 5
                        },
                        {
                            "type": "Benefit B",
                            "dollarSavings": 89.85,
                            "timeSavings": 47700,
                            "numUsed": 15
                        },
                        {
                            "type": "Benefit C",
                            "dollarSavings": 99.85,
                            "timeSavings": 46700,
                            "numUsed": 18
                        },
                        {
                            "type": "All Benefits",
                            "dollarSavings": 189.70,
                            "timeSavings": 94400,
                            "numUsed": 38
                        }

SOLVED:

{% assign numbers = data.Benefits | sort: 'numUsed'  %}
    {% for nums in numbers %}
    {% endfor %}
    {% assign benefits = data. data.Benefits | sort: 'numUsed'  %}
    {% for name in benefits %}
    {% endfor %}
    {% assign numsize = numbers | size %}
    {% assign numsizeminustwo = numsize | minus: 2 %}
    {% assign secondlasttype = benefits[{{numsizeminustwo}}].type %}
    {% assign secondlastnumber = numbers[{{numsizeminustwo}}].numUsed | floor %}
    
    Your favorite benefit this year was {{benefit_name}}, you used it {{secondlastnumber}} times

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM