Languages
[Edit]
EN

JavaScript - convert arguments object to sorted array

0 points
Created by:
Dragontry
731

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 ]

 

See also

  1. JavaScript - sort array

References

  1. Array.prototype.slice() - JavaScript | MDN
  2. Array.from() - JavaScript | MDN
  3. Array.prototype.sort() - JavaScript | MDN
  4. Array.prototype.slice() - JavaScript | MDN
  5. Function.prototype.call() - JavaScript | MDN

Alternative titles

  1. JavaScript - sort arguments and return them as array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join