EN
JavaScript - convert arguments object to sorted array
0 points
In this article, we would like to show you how to convert arguments
object to sorted array in JavaScript.
In this example, we use the rest parameter (...
) to convert passed arguments to a sorted array.
xxxxxxxxxx
1
const sortArguments = (args) => {
2
return args.sort((a, b) => a - b);
3
};
4
5
6
// Usage example:
7
8
console.log(sortArguments(3, 1, 2)); // [ 1, 2, 3 ]
In this example, we use Array
from()
method to create an array from arguments
object. Then we use sort()
method with a custom compare function to sort it.
xxxxxxxxxx
1
function sortArguments() {
2
return Array.from(arguments).sort(function(a, b) {
3
return a - b;
4
});
5
}
6
7
8
// Usage example:
9
10
console.log(sortArguments(3, 1, 2)); // [ 1, 2, 3 ]
In this example, we call the slice()
method on arguments
object to create an array from it. Then we use sort()
method to sort the array.
xxxxxxxxxx
1
function sortArguments() {
2
var args = Array.prototype.slice.call(arguments);
3
return args.sort();
4
}
5
6
7
// Usage example:
8
9
console.log(sortArguments(3, 1, 2)); // [ 1, 2, 3 ]