0

So I have my function uniteUnique. It should get the arguments and concatonate them to a single array. If there would be a specific amount of arguments for example 3, i would implement it like the function bellow

function uniteUnique(arr) {
  var args = [];
  var newArgs;
 for (var i = 0; i < arguments.length; i++) {
    args.push(arguments[i]);
    newArgs = args[0].concat(args[1], args[2]);
  }
  return newArgs ;
}

uniteUnique([1, 3, 2], [1, [5]], [2, [4]]);

But what if uniteUnique function would have 2 arguments or any other number.

uniteUnique([1, 2, 3], [5, 2, 1])

How to make my function know how many arguments it should concatonate, and how would it be implemented inside the concat() function ?

EDIT:

Output should look like this:

uniteUnique([1, 3, 2], [1, [5]], [2, [4]]) should return [1,3,1,1,[5],2,[4]]and uniteUnique([1, 2, 3], [5, 2, 1]) should return [1,2,3,5,2,1]

Giedrius
  • 603
  • 1
  • 6
  • 26

4 Answers4

2

I'm not sure if I fully understand your question, but: what about this simple solution?

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

The arguments object is not really an Array instance, and does not have any of the Array methods. So, arguments.slice(...) will not work because the arguments object does not have the slice method.

Instead, Arrays do have this method, and because the arguments object is very similar (...) to an array, the two are compatible. This means that we can use array methods with the arguments object. And array methods will return arrays rather than other argument objects.

For a more throughtful explanation please see this SO answer ...

UPDATE (to answer OP comment):

If you need deep merging, you can do:

function uniteUnique() {
  return Array.prototype.concat.apply([], arrays);
}

or even:

function uniteUnique() {
  return [].concat.apply([], arrays);
}

This should work since the dafaule value of Symbol.isConcatSpreadable is false, so concat() acts deeply...

Community
  • 1
  • 1
MarcoS
  • 17,323
  • 24
  • 96
  • 174
1

According to your examples you want to flatten arguments array. In ES6 you can use Rest parameters to get arguments array and Spread syntax to flatten it:

function uniteUnique(...args) {
  return [].concat(...args);
}
madox2
  • 49,493
  • 17
  • 99
  • 99
0

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/arguments

You can access the arguments variable to loop through all arguments passed to a given function.

Liam MacDonald
  • 301
  • 1
  • 9
0

Was able to solve this like that,

function uniteUnique(arr) {
   var myNewArray = [].concat.apply([], Array.prototype.slice.call(arguments));
  return myNewArray;
}
uniteUnique([1, 3, 2], [1, [5]], [2, [4]]) ;
Giedrius
  • 603
  • 1
  • 6
  • 26