1

Here I want to get maximum value of this multi dimensional array where tax_value is greater .

0:{id: "61", tax_value: "2.00000000"}
1:{id: "81", tax_value: "12.00000000"}

Here I am getting the array using this code.

 var array = new Array();
        if (typeof $('select[id^=item_tax]') !== "undefined")
        {
            $('select[id^=item_tax]').each(function (i, e)
            {
                if ($(e).val() > 0)
                {
                    array.push({id: $(e).val(), tax_value: $(e).find('option:selected').data('value')});
                }
            });


        }
        console.log(array);//multi dimensional array is coming as output

How to get maximum value from this array.

1

3 Answers 3

5

For returning the max tax_value, use map

var maxTaxValue = Math.max.apply( null, array.map( s => s.tax_value ) );

For returning the entire object with max tax_value.

var obj = array.find( s => s.tax_value == maxTaxValue )
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the new ES6 functions to get the max tax value but you can also get the max while doing the loop.

No need for additional loop or function.

var array = new Array();
var maxValue = 0; //Init the max variable
if (typeof $('select[id^=item_tax]') !== "undefined")
{
    $('select[id^=item_tax]').each(function (i, e)
    {
        if ($(e).val() > 0)
        {
                array.push({id: $(e).val(), tax_value: $(e).find('option:selected').data('value')});
        }

        //Test weather the current tax is greater. Assign the value
        var taxValue = Number( $(e).find('option:selected').data('value') );
        if ( maxValue < taxValue ) maxValue = taxValue;
    });
}

console.log( maxValue );

Comments

0

Didn't you try in this way. You can get an array which has each row's maximum. after that you can get the overal maximum from it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.