[javascript] How can I convert the "arguments" object to an array in JavaScript?

The arguments object in JavaScript is an odd wart—it acts just like an array in most situations, but it's not actually an array object. Since it's really something else entirely, it doesn't have the useful functions from Array.prototype like forEach, sort, filter, and map.

It's trivially easy to construct a new array from an arguments object with a simple for loop. For example, this function sorts its arguments:

function sortArgs() {
    var args = [];
    for (var i = 0; i < arguments.length; i++)
        args[i] = arguments[i];
    return args.sort();
}

However, this is a rather pitiful thing to have to do simply to get access to the extremely useful JavaScript array functions. Is there a built-in way to do it using the standard library?

This question is related to javascript arrays sorting arguments variadic-functions

The answer is


The Arguments object is only available inside a function body. Although you can index the Arguments Object like an array, it is not an array. It does not have any array properties other than length.

_x000D_
_x000D_
// function arguments length 5_x000D_
function properties(a,b,c,d,e){_x000D_
var function_name= arguments.callee.name_x000D_
var arguments_length= arguments.length;_x000D_
var properties_length=  properties.length; _x000D_
var function_from= properties.caller.name;_x000D_
console.log('I am the function name: '+ function_name);_x000D_
console.log('I am the function length, I am function spacific: '+ properties_length); _x000D_
console.log('I am the arguments length, I am context/excution spacific: '+ arguments_length);_x000D_
console.log('I am being called From: '+  function_from );_x000D_
}_x000D_
_x000D_
// arguments 3_x000D_
function parent(){_x000D_
properties(1,2,3);_x000D_
}_x000D_
_x000D_
//arguments length 3 because execution spacific_x000D_
parent();
_x000D_
_x000D_
_x000D_

Although it can be indexed like an array as you can see in this example:

_x000D_
_x000D_
function add(){_x000D_
_x000D_
var sum=0;_x000D_
_x000D_
for(var i=0; i< arguments.length;i++){_x000D_
_x000D_
sum = sum + arguments[i];_x000D_
_x000D_
}_x000D_
_x000D_
return sum;_x000D_
_x000D_
}_x000D_
_x000D_
console.log(add(1,2,3));
_x000D_
_x000D_
_x000D_

However, the Arguments object is not an array and does not have any other properties other than length.

You can convert the arguments object into an array at which point you can access the Arguments object.

There are many ways you can access the arguments object inside a function body, and these include:

  1. you can call the Array.prototoype.slice.call method.

Array.prototype.slice.call(arguments)

_x000D_
_x000D_
function giveMeArgs(arg1,arg2){_x000D_
_x000D_
var args = Array.prototype.slice.call(arguments);_x000D_
return args_x000D_
}_x000D_
_x000D_
console.log( giveMeArgs(1,2));
_x000D_
_x000D_
_x000D_

  1. you can use the array literal

[].slice.call(arguments).

_x000D_
_x000D_
function giveMeArgs(arg1,arg2){_x000D_
_x000D_
var args = [].slice.call(arguments);_x000D_
_x000D_
return args;_x000D_
_x000D_
}_x000D_
_x000D_
console.log( giveMeArgs(1,2) );
_x000D_
_x000D_
_x000D_

  1. you can use Rest ...

_x000D_
_x000D_
function giveMeArgs(...args){_x000D_
_x000D_
return args;_x000D_
_x000D_
}_x000D_
_x000D_
console.log(giveMeArgs(1,2))
_x000D_
_x000D_
_x000D_

  1. you can use spread [...]

_x000D_
_x000D_
function giveMeArgs(){_x000D_
_x000D_
var args = [...arguments];_x000D_
return args;_x000D_
_x000D_
}_x000D_
_x000D_
console.log(giveMeArgs(1,2));
_x000D_
_x000D_
_x000D_

  1. you can use Array.from()

_x000D_
_x000D_
function giveMeArgs(){_x000D_
_x000D_
var args = Array.from(arguments);_x000D_
_x000D_
return args;_x000D_
_x000D_
}_x000D_
_x000D_
console.log(giveMeArgs(1,2));
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
function sortArgs(...args) {_x000D_
  return args.sort(function (a, b) { return a - b; });_x000D_
}_x000D_
_x000D_
document.body.innerHTML = sortArgs(1, 2, 3, 4).toString();
_x000D_
_x000D_
_x000D_


 function x(){
   var rest = [...arguments]; console.log(rest);return     
   rest.constructor;
 };
 x(1,2,3)

I tried simple destructing technique


Another Answer.

Use Black Magic Spells:

function sortArguments() {
  arguments.__proto__ = Array.prototype;
  return arguments.slice().sort();
}

Firefox, Chrome, Node.js, IE11 are OK.


Here is benchmark of several methods converting arguments into array.

As for me, the best solution for small amount of arguments is:

function sortArgs (){
  var q = [];
  for (var k = 0, l = arguments.length; k < l; k++){
    q[k] = arguments[k];
  }
  return q.sort();
}

For other cases:

function sortArgs (){ return Array.apply(null, arguments).sort(); }

Although rest parameters work well, if you want to continue to use arguments for some reason, consider

function sortArgs() {
  return [...arguments].sort()
}

[...arguments] can be considered a sort of alternative to Array.from(arguments), which also works perfectly well.

An ES7 alternative is an array comprehension:

[for (i of arguments) i].sort()

This could be easiest if you want to process or filter the arguments prior to sorting:

[for (i of arguments) if (i % 2) Math.log(i)].sort()

Here's a clean and concise solution:

_x000D_
_x000D_
function argsToArray() {_x000D_
  return Object.values(arguments);_x000D_
}_x000D_
_x000D_
// example usage_x000D_
console.log(_x000D_
  argsToArray(1, 2, 3, 4, 5)_x000D_
  .map(arg => arg*11)_x000D_
);
_x000D_
_x000D_
_x000D_

Object.values( ) will return the values of an object as an array, and since arguments is an object, it will essentially convert arguments into an array, thus providing you with all of an array's helper functions such as map, forEach, filter, etc.


You can create a reusable function to do it with any arguments, the simplest one is something like this:

function sortArgs() {
  return [...arguments].sort();
}

sortArgs('ali', 'reza', 1, 2, 'a'); //[1, 2, "a", "ali", "reza"];

Spread syntax can be used in ES6 and above...

But if you'd like to use something compatible with ES5 and below, you can use Array.prototype.slice.call, so you code looks like this:

function sortArgs() {
  return Array.prototype.slice.call(arguments).sort();
}

sortArgs('ali', 'reza', 1, 2, 'a'); //[1, 2, "a", "ali", "reza"];

There are also few other ways to do this, for Example using Array.from or loop through the arguments and assign them to a new array...


Try using Object.setPrototypeOf()

Explanation: Set prototype of arguments to Array.prototype

_x000D_
_x000D_
function toArray() {_x000D_
  return Object.setPrototypeOf(arguments, Array.prototype)_x000D_
} _x000D_
_x000D_
console.log(toArray("abc", 123, {def:456}, [0,[7,[14]]]))
_x000D_
_x000D_
_x000D_


Explanation: Take each index of arguments , place item into an array at corresponding index of array.

could alternatively use Array.prototype.map()

_x000D_
_x000D_
function toArray() {_x000D_
  return [].map.call(arguments, (_,k,a) => a[k])_x000D_
} _x000D_
_x000D_
console.log(toArray("abc", 123, {def:456}, [0,[7,[14]]]))
_x000D_
_x000D_
_x000D_


Explanation: Take each index of arguments , place item into an array at corresponding index of array.

for..of loop

_x000D_
_x000D_
function toArray() {_x000D_
 let arr = []; for (let prop of arguments) arr.push(prop); return arr_x000D_
} _x000D_
_x000D_
console.log(toArray("abc", 123, {def:456}, [0,[7,[14]]]))
_x000D_
_x000D_
_x000D_


or Object.create()

Explanation: Create object, set properties of object to items at each index of arguments; set prototype of created object to Array.prototype

_x000D_
_x000D_
function toArray() {_x000D_
  var obj = {};_x000D_
  for (var prop in arguments) {_x000D_
    obj[prop] = {_x000D_
      value: arguments[prop],_x000D_
      writable: true,_x000D_
      enumerable: true,_x000D_
      configurable: true_x000D_
    }_x000D_
  } _x000D_
  return Object.create(Array.prototype, obj);_x000D_
}_x000D_
_x000D_
console.log(toArray("abc", 123, {def: 456}, [0, [7, [14]]]))
_x000D_
_x000D_
_x000D_


function sortArg(){
var args = Array.from(arguments); return args.sort();
}

_x000D_
_x000D_
 function sortArg(){_x000D_
    var args = Array.from(arguments); _x000D_
    return args.sort();_x000D_
    }_x000D_
 _x000D_
 console.log(sortArg('a', 'b', 1, 2, '34', 88, 20, '19', 39, 'd', 'z', 'ak', 'bu', 90));
_x000D_
_x000D_
_x000D_


Lodash:

var args = _.toArray(arguments);

in action:

(function(){ console.log(_.toArray(arguments).splice(1)); })(1, 2, 3)

produces:

[2,3]

Benshmarck 3 methods :

function test()
{
  console.log(arguments.length + ' Argument(s)');

  var i = 0;
  var loop = 1000000;
  var t = Date.now();
  while(i < loop)
  {
      Array.prototype.slice.call(arguments, 0); 
      i++;
  }
  console.log(Date.now() - t);


  i = 0,
  t = Date.now();
  while(i < loop)
  {
      Array.apply(null, arguments);
      i++;
  }
  console.log(Date.now() - t);

  i = 0,
  t = Date.now();
  while(i < loop)
  {
      arguments.length == 1 ? [arguments[0]] : Array.apply(null, arguments);
      i++;
  }
  console.log(Date.now() - t);
}

test();
test(42);
test(42, 44);
test(42, 44, 88, 64, 10, 64, 700, 15615156, 4654, 9);
test(42, 'truc', 44, '47', 454, 88, 64, '@ehuehe', 10, 64, 700, 15615156, 4654, 9,97,4,94,56,8,456,156,1,456,867,5,152489,74,5,48479,89,897,894,894,8989,489,489,4,489,488989,498498);

RESULT?

0 Argument(s)
256
329
332
1 Argument(s)
307
418
4
2 Argument(s)
375
364
367
10 Argument(s)
962
601
604
40 Argument(s)
3095
1264
1260

Enjoy !


In ECMAScript 6 there's no need to use ugly hacks like Array.prototype.slice(). You can instead use spread syntax (...).

_x000D_
_x000D_
(function() {_x000D_
  console.log([...arguments]);_x000D_
}(1, 2, 3))
_x000D_
_x000D_
_x000D_

It may look strange, but it's fairly simple. It just extracts arguments' elements and put them back into the array. If you still don't understand, see this examples:

_x000D_
_x000D_
console.log([1, ...[2, 3], 4]);_x000D_
console.log([...[1, 2, 3]]);_x000D_
console.log([...[...[...[1]]]]);
_x000D_
_x000D_
_x000D_

Note that it doesn't work in some older browsers like IE 11, so if you want to support these browsers, you should use Babel.


Use Array.from(), which takes an array-like object (such as arguments) as argument and converts it to array:

_x000D_
_x000D_
(function() {_x000D_
  console.log(Array.from(arguments));_x000D_
}(1, 2, 3));
_x000D_
_x000D_
_x000D_

Note that it doesn't work in some older browsers like IE 11, so if you want to support these browsers, you should use Babel.


It's also worth referencing this Bluebird promises library wiki page that shows how to manage the arguments object into array in a way that makes the function optimizable under V8 JavaScript engine:

function doesntLeakArguments() {
    var args = new Array(arguments.length);
    for(var i = 0; i < args.length; ++i) {
        args[i] = arguments[i];
    }
    return args;
}

This method is used in favor of var args = [].slice.call(arguments);. The author also shows how a build step can help reduce the verbosity.


function sortArgs(){ return [].slice.call(arguments).sort() }

// Returns the arguments object itself
function sortArgs(){ return [].sort.call(arguments) }

Some array methods are intentionally made not to require the target object to be an actual array. They only require the target to have a property named length and indices (which must be zero or larger integers).

[].sort.call({0:1, 1:0, length:2}) // => ({0:0, 1:1, length:2})

If you're using jQuery, the following is a good deal easier to remember in my opinion:

function sortArgs(){
  return $.makeArray(arguments).sort();
}

This is a very old question, but I think I have a solution that is slightly easier to type than previous solutions and doesn't rely on external libraries:

function sortArguments() {
  return Array.apply(null, arguments).sort();
}

I recommend using ECMAScript 6 spread operator, which will Bind trailing parameters to an array. With this solution you don't need to touch the arguments object and your code will be simplified. The downside of this solution is that it does not work across most browsers, so instead you will have to use a JS compiler such as Babel. Under the hood Babel transforms arguments into a Array with a for loop.

function sortArgs(...args) {
  return args.sort();
}

If you can not use a ECMAScript 6, I recommend looking at some of the other answers such as @Jonathan Fingland

function sortArgs() {
    var args = Array.prototype.slice.call(arguments);
    return args.sort();
}

Use:

function sortArguments() {
  return arguments.length === 1 ? [arguments[0]] :
                 Array.apply(null, arguments).sort();
}

Array(arg1, arg2, ...) returns [arg1, arg2, ...]

Array(str1) returns [str1]

Array(num1) returns an array that has num1 elements

You must check number of arguments!

Array.slice version (slower):

function sortArguments() {
  return Array.prototype.slice.call(arguments).sort();
}

Array.push version (slower, faster than slice):

function sortArguments() {
  var args = [];
  Array.prototype.push.apply(args, arguments);
  return args.sort();
}

Move version (slower, but small size is faster):

function sortArguments() {
  var args = [];
  for (var i = 0; i < arguments.length; ++i)
    args[i] = arguments[i];
  return args.sort();
}

Array.concat version (slowest):

function sortArguments() {
  return Array.prototype.concat.apply([], arguments).sort();
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to sorting

Sort Array of object by object field in Angular 6 Sorting a list with stream.sorted() in Java How to sort dates from Oldest to Newest in Excel? how to sort pandas dataframe from one column Reverse a comparator in Java 8 Find the unique values in a column and then sort them pandas groupby sort within groups pandas groupby sort descending order Efficiently sorting a numpy array in descending order? Swift: Sort array of objects alphabetically

Examples related to arguments

docker build with --build-arg with multiple arguments ARG or ENV, which one to use in this case? How to have multiple conditions for one if statement in python Gradle task - pass arguments to Java application Angularjs - Pass argument to directive TypeError: method() takes 1 positional argument but 2 were given Best way to check function arguments? "Actual or formal argument lists differs in length" Python: Passing variables between functions Print multiple arguments in Python

Examples related to variadic-functions

Concatenate two slices in Go Possible heap pollution via varargs parameter How to pass an ArrayList to a varargs method parameter? Why use the params keyword? What do 3 dots next to a parameter type mean in Java? Can I pass an array as arguments to a method with variable arguments in Java? Java variable number or arguments for a method Is it possible to send a variable number of arguments to a JavaScript function? Variable number of arguments in C++? How to pass variable number of arguments to a PHP function