0

I have the array "arrs" with nested arrays like below:

let arrs = ["Apple", ["Peach", "Grape"], [["Pear", "Kiwi"], ["Lemon"]]];

Now, I want to convert the array "arrs" to the new array "newArr" without nested arrays like below:

let newArr = [ "Apple", "Peach", "Grape", "Pear", "Kiwi", "Lemon" ];

I created the code to convert "arrs" to "newArr" without nested arrays:

let newArr = [arrs[0], arrs[1][0], arrs[1][1], arrs[2][0][0], arrs[2][0][1], arrs[2][1][0]];

console.log(newArr); // [ "Apple", "Peach", "Grape", "Pear", "Kiwi", "Lemon" ]

This is the full runnable code:

let arrs = ["Apple", ["Peach", "Grape"], [["Pear", "Kiwi"], ["Lemon"]]];

let newArr = [arrs[0], arrs[1][0], arrs[1][1], arrs[2][0][0], arrs[2][0][1], arrs[2][1][0]];

console.log(newArr); // [ "Apple", "Peach", "Grape", "Pear", "Kiwi", "Lemon" ]

However, I want to make this code simpler, cooler or clever. Are there any ways to do this?

let newArr = [arrs[0], arrs[1][0], arrs[1][1], arrs[2][0][0], arrs[2][0][1], arrs[2][1][0]];

console.log(newArr); // [ "Apple", "Peach", "Grape", "Pear", "Kiwi", "Lemon" ]
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129

1 Answers1

1

You can use "flat()" with "2":

let arrs = ["Apple", ["Peach", "Grape"], [["Pear", "Kiwi"], ["Lemon"]]];

let newArr = arrs.flat(2);

console.log(newArr); // [ "Apple", "Peach", "Grape", "Pear", "Kiwi", "Lemon" ]

In addition, you can use "flat()" with "Infinity" for any depth of nested array.

let arrs = ["Apple", ["Peach", "Grape"], [["Pear", "Kiwi"], ["Lemon"]]];

let newArr = arrs.flat(Infinity);

console.log(newArr); // [ "Apple", "Peach", "Grape", "Pear", "Kiwi", "Lemon" ]
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129