Question

I have declared my array like var arrTest=[];

and i am adding some info to it and below is arrTest contents

[Object { minutes=78, start="some address1", end="end address2"}, Object { minutes=54, start="some address3", end="some address4"}, Object { minutes=21, start="some address5", end="some address6"}]

Now what i have to do to select the information with MINIMUM minutes i.e. minutes=21, start="some address5", end="some address6" With Jquery.

Any guidance will be highly appreciated..

thanks

Was it helpful?

Solution 2

You could make your own function that will return the minimum of an array from key. There is no necessarily way to use jQuery.

function getMin(arr, key) {
    // The object with minimum
    var obj;
    // The latest minimum on arr[i][key]
    var min = Number.MAX_VALUE;

    // Iteration through all objects
    for (var i = 0; i < arr.length; i++) {
        if(arr[i][key] < min) {
            obj = arr[i];
            min = arr[i][key];
        } // if end
    }

    return obj;
}

See more, example and run at: http://jsfiddle.net/mL8GA/

OTHER TIPS

Just loop and check:

var low = arrTest[0].minutes;
    index;

for (var i = 0; i < arrTest.length; i++) {
    if (arrTest[i].minutes < low) {
        low = arrTest[i].minutes;
        index = i;
    }
}

console.log("The lowest minutes are: " + low);
console.log("Located at the object at index of: " + index);

If you would like to use a library to handle this operation, you can check out underscore's sortBy function.

http://underscorejs.org/#sortBy

So, for your example, you have:

var arrTest = [
    {
        minutes : 78,
        start : "address1",
        end : "address2"
    }
    // ...
];

and you can use the sortBy function to sort like so:

var sortedArray = _.sortBy(arrTest, 'minutes');

and to find the min, you can choose the first:

return sortedArray[0];

Of course, this is fully sorting the array as opposed to just finding the min or max.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top