kilojoules kilojoules - 4 years ago 167
Javascript Question

Javascript dealing with unkown number of function arguments

My function needs to accept any number of lists, then output their symmetric difference.

sym([1, 2, 3], [5, 2, 1, 4])
should return
[3, 5, 4]
and
sym([1, 2, 5], [2, 3, 5], [3, 4, 5])
should return
[1, 4, 5]
. How can I deal with the unknown number of arguments? I thought that I could use the single variable
args
to create a list of lists, but that isn't working.

function isin(num,arra)
{
for (i=0; i<arra.length; i++)
{
if (num == arra[i]){return true;}
}
return false;
}

function sym(args) {
var syms = [];
console.log(args);
for (i=0; i<args.length; i++)
{
var ins = false;
for (j=0; j<args[i].length; j++)
{
for (k=i+1; k < args.length; k++)
{
if(isin(args[i][j], args[k]))
{
ins = true;
}
}
}
if (ins === false)
{
syms.push(args[i][j]);
}
}
return syms;
}
sym([1, 2, 3], [5, 2, 1, 4]);

Answer Source

use arguments, not args

and you dont need to have it in the function definition.

(note: Im assuming the rest of your code works once you actually get what youre expecting passed in)

so:

function sym() {
   var syms = [];
   console.log(arguments);
   for (i=0; i<argumentss.length; i++)
   {
     var ins = false;
     for (j=0; j<arguments[i].length; j++)
     {
       for (k=i+1; k < arguments.length; k++)
       {
         if(isin(arguments[i][j], arguments[k]))
         {
           ins = true;
         }
       }
     }
     if (ins === false)
     {
       syms.push(arguments[i][j]);
     }
   }
  return syms;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download