Javascript arguments.sort() throw error sort is not a function
Another way to do this is by declaring the arguments as an array.
var myArguments = [1, 1, 2, 3];
var sortedArguments = [];
Thus the highest() can be defined as;
function highest(myArguments)
{
return myArguments.sort(function(a,b)
{
return b - a;
});
}
sortedArguments = highest(myArguments);
Because arguments
has no sort
method. Be aware that arguments
is not an Array
object, it's an array-like Arguments
object.
However, you can use Array.prototype.slice
to convert arguments
to an array; and then you will be able to use Array.prototype.sort
:
function highest(){
return [].slice.call(arguments).sort(function(a,b){
return b - a;
});
}
highest(1, 1, 2, 3); // [3, 2, 1, 1]
use spread syntax to convert arguments to a real Array:
function highest(...arguments){
return arguments.sort(function(a,b){
return b - a;
});
}
highest(1, 1, 2, 3);
Output: (4) [3, 2, 1, 1]