1

I need to send multiple array as parameters, not only 2 (yes I'm using _underscore in order to check for duplicate entries)

function arrayMerge(arr1, arr2) {
    arr1 = Object.prototype.toString.call(arr1) === '[object Array]' ? arr1 : [];
    arr2 = Object.prototype.toString.call(arr2) === '[object Array]' ? arr2 : [];   
    return _.uniq(arr1.concat(arr2));
}

How can I achieve this ? I would like to send not 2, but multiples arrays as parameters.

2
  • You can randomly refer to any function argument via the "builtin" arguments array: arguments[0] === arr1 in your case. Iterate over arguments to get each array. Commented Dec 23, 2014 at 20:43
  • You can directly use _.union() for that _.union([1,4,6,9], [1,4,12,5], [5,0,10,100], [1]).join("") === _.uniq([1,4,6,9].concat([1,4,12,5]).concat([5,0,10,100]).concat([1])).join("") Commented Dec 23, 2014 at 20:53

3 Answers 3

1

The version that also checks for array type like in your original code:

function arrayMerge() {
    return _.chain(arguments).filter(_.isArray).flatten().unique().value();
}

The demo is below.

function arrayMerge() {
    return _.chain(arguments).filter(_.isArray).flatten().unique().value();
}

var result = arrayMerge([1,2,3],[1,3,4],'test',[2,3,4,5]);

document.write(JSON.stringify(result));
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

1

You can use arguments. The variable arguments is an array of all the arguments passed to a function. So you can try this:

function merge() {
  return _.uniq(Array.prototype.concat.apply([], arguments));
}

I have no experience with underscore but this should work.

Due to the behavior of concat, calling merge([3, 4, 5], null, 6) will result in [3, 4, 5, null, 6].

To ensure that all are arrays:

for (var i = 0; i < arguments.length; ++i) {
  if (Object.prototype.toString.call(arguments[i]) !== '[object Array]') {
    throw new Error(arguments[i] + " is not an array"); // Or do whatever you want
  }
}

1 Comment

@soktinpk You might want to leave a comment for the OP, it looks like they've never accepted an answer before.
1

Soktinpk's answer is best for ES5.

If you are able to use ES6, you can make it a bit more explicit using rest parameters

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.