2

I'm trying to merge the elements of the array into one big array. But I receive a message saying:

ReferenceError: reduce is not defined

Here is my code:

var arrays = [[1, 2, 3], [4, 5], [6]];

console.log(reduce(arrays, function(arrayOne, arrayTwo){
    return arrayOne.concat(arrayTwo);
}, 0));
Qantas 94 Heavy
  • 15,410
  • 31
  • 63
  • 82
  • possible duplicate of [Merge/flatten an Array of Arrays in JavaScript?](http://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays-in-javascript) – Qantas 94 Heavy Mar 14 '15 at 00:25

2 Answers2

1

reduce() is only defined on Arrays, you cannot call it by itself:

arrays.reduce(
   function (a, b) { return a.concat(b); }
);
// Array [ 1, 2, 3, 4, 5, 6 ]
Hunter McMillen
  • 56,682
  • 21
  • 115
  • 164
1

reduce() is a method of the Array object, so you must use arrays.reduce().

Moreover, since your initial value is set to 0 (the 2nd parameter), you can't use arrayOne.concat on it, since it's not an array, so you must set the initial value to [].

var arrays = [[1, 2, 3], [4, 5], [6]];

console.log(arrays.reduce(function(arrayOne, arrayTwo){
    return arrayOne.concat(arrayTwo);
}, []));

Note that calling Array.flat is easier:

var arrays = [[1, 2, 3], [4, 5], [6]];
// If you expect a multi-level nested array, you should increase the depth.
var depth = 1;

console.log(arrays.flat(depth));
Benoit Esnard
  • 1,959
  • 1
  • 22
  • 31