0

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

1
  • 1
    Is this explicitly required to be in JQuery? From my understanding, JQuery wouldn't actually help you to do this. Commented Dec 10, 2013 at 22:07

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

0

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.

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.