Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
Convert the array with nested arrays to the new array without nested arrays (JavaScript)

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" ]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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" ]

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!