Skip to content

Flatten array JavaScript recursion | Example code

  • by

Use concat() and push() methods with for loop to get Flatten array in JavaScript recursion. The solution below uses array.concat(…) to combine both the result of the recursion (going down the tree), and also to combine the results of processing the rest of the list (at the same level).

Flatten array JavaScript recursion

Simple example code when calling flatten recursively, you need to pass arr[i] to it and then concat the result with newArr.

Flatten nested arrays while preserving the order, e.g. [[1, 2], 3, [4, [[5]]]] should be converted to [1, 2, 3, 4, 5].

<!DOCTYPE html>
<html>
<body>

  <script>
    function flatten (arr) {
      var newArr = [];
      for (var i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
          newArr = newArr.concat(flatten(arr[i]));
        } else {
          newArr.push(arr[i]);
        }
      }
      return newArr;
    }

    var res = flatten([[1, 2], 3, [4, [[5]]]]);

    console.log(res)
  </script>

</body>
</html> 

Output:

Here’s a more modern version:

To flatten an array using recursion in JavaScript, you can create a function that checks each element of the array and, if it is an array, recursively calls itself on that subarray. If the element is not an array, it is added to the result array.

function flatten(items) {
  const flat = [];

  items.forEach(item => {
    if (Array.isArray(item)) {
      flat.push(...flatten(item));
    } else {
      flat.push(item);
    }
  });

  return flat;
}

Here’s how the function works:

  1. It creates an empty array to store the flattened result.
  2. It iterates over each element in the array using the forEach method.
  3. For each element, it checks if it is an array using the Array.isArray method.
  4. If the element is an array, the function recursively calls itself on that subarray using concat to add the flattened result to the result array.
  5. If the element is not an array, it is added to the result array using the push method.
  6. Finally, the function returns the flattened result array.

The clean way to flatten an Array in 2019 with ES6 is flat():

const array = [1, 1, [2, 2], [[3, [4], 3], 2]]

// All layers
array.flat(Infinity) // [1, 1, 2, 2, 3, 4, 3, 2]

// Varying depths
array.flat() // [1, 1, 2, 2, Array(3), 2]

array.flat(2) // [1, 1, 2, 2, 3, Array(1), 3, 2]
array.flat().flat() // [1, 1, 2, 2, 3, Array(1), 3, 2]

array.flat(3) // [1, 1, 2, 2, 3, 4, 3, 2]
array.flat().flat().flat() // [1, 1, 2, 2, 3, 4, 3, 2]

Comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *