0

The below given code gives an error arguments.sort is not a function. Is it because arguments object cannot be altered directly? Or is it something else.

Any help would be appreciated.

function highest()
{ 
    return arguments.sort(function(a,b){ 
         return b - a; 
    }); 
} 
assert(highest(1, 1, 2, 3)[0] == 3, "Get the highest value."); 
assert(highest(3, 1, 2, 3, 4, 5)[1] == 4, "Verify the results.");

The assert function is as follows (Just in case)

function assert(pass, msg){
   var type = pass ? "PASS" : "FAIL";
   jQuery("#results").append("<li class='" + type + "'><b>" + type + "</b> " + msg + "</li>");
}

3 Answers 3

4

Try this:

return [].sort.call(arguments, function(a, b) {
   return b - a;
})

Edit: As @Esailija pointed out, this doesn't return a real array, it just returns the arguments object which is an array-like object. It's fine for iterating and accessing properties by index, but that's about it.

Sign up to request clarification or add additional context in comments.

2 Comments

But this doesn't return an array :x
@Esailija: Right, didn't notice that, it returns an arguments object. It should be fine for this case, but yeah OP might want an actual array.
2

It is because arguments is not an array and doesn't have the sort method.

You can use this trick to convert it to an array:

function highest()
{ 
    return [].slice.call(arguments).sort(function(a,b){ 
         return b - a; 
    }); 
} 

Comments

0

You highest function isn't passing any argument inside

function highest(arguments)
{ 
    return arguments.sort(function(a,b){ 
         return b - a; 
    }); 
} 

and should work with an array

highest([1, 1, 2, 3])[0]

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.