Digvijay
Digvijay

Reputation: 3271

How to make nested array into a single array in javascript

I got stuck in some problem and unable to get any idea of how to resolve it.As I have a nested array given below:

arr = [1,2,3,4,5,6,[7,8,9,[10,[21,22,[24,25,26],23],11],12,13],14,15,16,[17,18],19,20]

On using flat() method below method:

arr.flat()

it gives below output:

[1,2,3,4,5,6,7,8,9,[ 10, [ 21, 22, [Array], 23 ],11 ],12,13,14,15,16,17,18,19,20]

How can I convert this nested array into a single array.Someone let me know.

Upvotes: 2

Views: 731

Answers (1)

DecPK
DecPK

Reputation: 25408

You can use the flat method here.

arr.flat(Infinity);

const arr = [
  1,
  2,
  3,
  4,
  5,
  6, [7, 8, 9, [10, [21, 22, [24, 25, 26], 23], 11], 12, 13],
  14,
  15,
  16, [17, 18],
  19,
  20,
];

const result = arr.flat(Infinity);
console.log(result);

Upvotes: 4

Related Questions