0

I have nested Array (arrays in parent array).

let myArray = [ [], [ 8300, 8400, 8500, 8600 ], [ 6379 ], [ 5672 ], [ 27017 ] ]

I am trying to mix all of this into one array .

let targetArray = [8300, 8400, 8500, 8600, ..., 27017]

I used reduce and concat to achieve this goal.

let unique_array = myArray.map(p=>{p}).reduce((prev, next)=>{prev && prev.concat(next))

but I am getting this error:

Uncaught Error TypeError: Reduce of empty array with no initial value

so my question is how can I skip this error?

Babak Abadkheir
  • 2,222
  • 1
  • 19
  • 46
  • 1
    You can use `.flat()` or a polyfill if your browser doesn't support it – Nick Parsons Dec 24 '19 at 09:30
  • 2
    You need to provide an initial value to reduce, and in this case, it would be an empty array, i.e. `reduce(() => {/**/}, [])` – Kobe Dec 24 '19 at 09:33
  • @Kobe _"You need to provide..."_ - No, you don't have to. The initial value is [optional](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce). – Andreas Dec 24 '19 at 09:43
  • Your example doesn't throw that error. The error only occurs when you call `.reduce()` on an _empty array_ without providing an initial value -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value – Andreas Dec 24 '19 at 09:44
  • 1
    Your approach was right. You can do it like this: `let targetArray = myArray.reduce(function(acc, cur) { return acc.concat(cur); }, []);` – Mehulkumar Dec 24 '19 at 09:51

2 Answers2

1

Why not Array.prototype.flat():

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

let myArray = [ [], [ 8300, 8400, 8500, 8600 ], [ 6379 ], [ 5672 ], [ 27017 ] ];

let targetArray = myArray.flat();

console.log(targetArray);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

Or you can do this

unique_array = myArray.reduce((prev, next)=>([...prev,...next]),[])

AppleJam
  • 1,039
  • 8
  • 18