I want to define a function .flatten that flattens several elements into one single array. I know that the following is not possible, but essentially I would like to do this:
var flatten = function() {
var flattened = arguments.reduce(function(acc, elem) { return acc.concat(elem) }, []);
return flattened;
};
var arr = [[1,2,3], 4, 5, [6, 7]];
console.log(flatten(arr)) // => [1,2,3,4,5,6,7]
I get the following error:
TypeError: arguments.reduce is not a function
I understand that the above error is because arguments is only array-like, so it does not have the full capabilities of a true array. So there is the following, but I'm wondering if there is something even cleaner:
var flatten = function() {
var flattened = [].reduce.call(arguments, function(acc, elem) { return acc.concat(elem) });
return flattened;
};
Any good way to rewrite .flatten using .reduce()?
NOTE: I know there are many other ways that you can flatten arrays in javascript, but what I was wondering about here is how to do so with specifically arguments.
reduceis not good for flattening arrays. Also, your code works..call()you forgot to pass an empty array as the second argument to.reduce().arguments. All you have to do is useArray.prototypewith whatever, and thencallusingarguments.