0

I have an array of objects. I want to find the "maximum" of this array based on a function that returns whichever object is bigger when given 2 objects.

function comparison(first, second) {
    // ... arbitrary comparison based on properties...
    return first; // or second
}

var a = [obj1, obj2, obj3];
var maxObj = ????(comparison);

What do I fill in here? What's elegant and short?

3 Answers 3

2

Something like this should be quicker than sort (depending on the data):

/*
  values: array of values to test.
      fn: function that takes two arguements and returns true if the first is bigger.
*/
var maximum = function(values, fn) {
    var currentValue, maxValue = values.pop();
    while(values.length)
        maxValue = fn(maxValue, currentValue = values.pop()) ? maxValue : currentValue;
    return maxValue;
}

Examples: http://jsfiddle.net/SaBJ4/2/

Even better, use Array.reduce:

var a = ['abc', 'defg', 'highlkasd', 'ac', 'asdh'];
a.reduce(function(a, b) { return a.length > b.length ? a : b; }); // highlkasd
Sign up to request clarification or add additional context in comments.

2 Comments

The downside is that that function modifies its input, that may or may not be a problem.
+1 for reduce but you'll need to special-case empty arrays and arrays with only one element (depending on the behavior of comparison), using an explicit initial value can help.
1

What's wrong with the obvious approach?

for(var i = 0, max; i < a.length; ++i)
    max = typeof max == 'undefined' ? a[i] : comparison(a[i], max);

Wrap that up however you like.


Or you can take advantage of the fact that a = []; x = a[0] leaves you with undefined in x and do it RobG's way:

for(var i = 1, max = a[0]; i < a.length; ++i)
    max = comparison(a[i], max);

That nicely avoids a bunch of typeof operators and comparisons that you really don't need.

3 Comments

Why not initialise max as a[0] and i as 1 and avoid the ternary expression?
@mu blush Of course you're right; that doesn't apply at all to this case. Deleting my silly comment.
@RobG: That's a great idea and even behaves properly when the array is empty, I guess I still have old habits from C.
0
[obj,obj,obj].sort(comparison)

// aka
var sorted = [obj,obj,obj].sort(function(a,b){
  // return 1/0/-1
});

Then either pop the top or bottom element off (however you're sorting) to get the "max" object.

Array.Sort

1 Comment

This is effective, but inefficient; finding the max should be O(n) while this is O(n^2) (worse case).

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.