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.
1. Using rest parameter (ES6)
In this example, we use the rest parameter (...) to convert passed arguments to a sorted array.
// ONLINE-RUNNER:browser;
const sortArguments = (...args) => {
return args.sort((a, b) => a - b);
};
// Usage example:
console.log(sortArguments(3, 1, 2)); // [ 1, 2, 3 ]
2. Using from() and sort() methods (ES6)
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.
// ONLINE-RUNNER:browser;
function sortArguments() {
return Array.from(arguments).sort(function(a, b) {
return a - b;
});
}
// Usage example:
console.log(sortArguments(3, 1, 2)); // [ 1, 2, 3 ]
3. Using Array slice() with Function call() (ES5)
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.
// ONLINE-RUNNER:browser;
function sortArguments() {
var args = Array.prototype.slice.call(arguments);
return args.sort();
}
// Usage example:
console.log(sortArguments(3, 1, 2)); // [ 1, 2, 3 ]