How to Convert Arguments Object to an Array

The arguments object is an Array-like object which represents the arguments passed in when executing a function. To convert it to Array, there are several methods that we are going to discuss in the scope of this article.

Array.from

There is method in ECMAScript 2015 that converts an arguments into an array. You can use the Array.from() or the spread operator like this:

function sortArgs(...args) {
  return args.sort(function (a, b) {
    return a - b;
  });
}
console.log(sortArgs(21, 5, 4, 8).toString());

The Array.from() method is used to create a new, shallow-copied Array instance from an array-like or iterable object.

Rest Parameters

If you use ES6 the rest parameters can help you with the task:

function sortArgs(...args) {
  return args.sort(function (a, b) {
    return a - b;
  });
}
console.log(sortArgs(21, 5, 4, 8).toString());

The rest parameter syntax allows representing an indefinite number of arguments as an Array.

slice()

When the slice() method is called normally, it means that this is an Array, and the method iterates over that Array and works properly.

The this in the slice() function is accepted as an Array as when you call the following the object automatically becomes the value of this in the method():

object.method();

Let’s consider the following case:

[1,2,3].slice()

The [1,2,3] Array set will be as the value of this in slice().

But if you substitute something else, for example, that has a numeric .length property or a set of properties that are numeric indices as the this value, it should work. This kind of object is often called an array-like object.

The Array-like object means that arguments has a length property and properties indexed from zero, but it doesn't have the built-in methods of Array, such as forEach() and map().

The call() and apply() methods allow setting the value of this in a function manually. If you set the value of this in slice() to an array-like object, it will consider it as an Array, and perform the same action as in the case of arrays.

Let’s take a look at this example:

let obj = {
  '0': 'zero',
  '1': 'one',
  '2': 'two',
  '3': 'three',
  length: 4
};
let sliced = Array.prototype.slice.call(obj, 2);
console.log(sliced);

This is not an Array, but if you can set it as the this value of slice(), then it will work as it looks like an Array.

Here is how the slice() method works when you set an arguments object as the this value.

Do you find this helpful?

Related articles