Search⌘ K
AI Features

Discussion: The Flat Earth Society

Explore how to flatten nested arrays in JavaScript by using the concat method combined with apply and the modern flat() method. Understand how these techniques work, their differences, and how to control the depth of flattening. This lesson helps you improve array manipulation skills and write cleaner, more effective JavaScript code.

Verifying the output

Now, it's time to execute the code and observe the output.

Javascript (babel-node-es2024)
const nestedArray = ["apple", ["blueberry", "blackberry"],
["tangerine", "orange"], "grape"];
const newArr = [].concat.apply([], nestedArray);
console.log(newArr);

Code explanation

This JavaScript code is all about flattening an array of arrays. First, we have an array called nestedArray. It contains four elements: two strings and two subarrays. The second line of code does the magic of flattening the array. Here’s how it works:

  1. [] creates an ...