Flatten Array

Easy ImportantPayPal

Prompt

In JavaScript, the task of flattening an array, that is, reducing an array with nested arrays into a single-level array, is a common operation. However, let's imagine that the native methods to do this, like flat(), aren't available.

Your task is to create a custom function that takes a multi-dimensional array as input and returns a single-dimensional array as output. This function should work for any level of nested arrays. Please write your solution in JavaScript and briefly discuss your approach.

Note: When flattening an array, it's common to include all elements of the original array in the flattened output, regardless of their value. This includes null and undefined.

Playground

Hint 1

In your flattening process, you'll need to determine whether an element in the inputArray is itself an array. The Array.isArray function can be very useful here to check if an element needs further flattening.

Hint 2

When you encounter a nested array within your inputArray, think about how recursion can be used. How can you call flattenArray itself to handle these nested arrays?

Hint 3

For elements in the array that are not themselves arrays, add them directly to your result array.

Solution

Explanation

The flattenArray function uses recursion to transform a nested array into a single-dimensional array. Let's understand how it works:

function flattenArray(arr) {
let result = [];

arr.forEach((element) => {
if (Array.isArray(element)) {
result.push(...flattenArray(element));
} else {
result.push(element);
}
});

return result;
}

The function works in following steps:

  1. We create an empty array result to store our flattened elements
  2. We iterate through each element of the input array using forEach on the input array
  3. For each element, we check if it's an array using Array.isArray()
  4. If the element is an array:
    • We recursively call flattenArray on it
    • We spread ... the returned flattened array into our result
  5. If the element is not an array:
    • We directly push it to our result array
  6. Finally, we return the flattened array

Dry Run

For example, with input [1, [2, [3, 4]]]:

  • First iteration finds 1: pushes 1 to result because it's not an array
  • Second iteration finds [2, [3, 4]]: recursively flattens it because it's an array
    • Inner call first iteration finds 2: pushes 2 to result because it's not an array
    • Inner call second iteration finds [3, 4]: recursively flattens it because it's an array
      • Innermost call pushes 3, then 4 to result because they are not arrays
  • Final result: [1, 2, 3, 4]

The spread operator (...) is essential here as it helps unpack the nested arrays into individual elements, preventing any remaining nested structures in our final result.

Notes

Array.isArray()

Array.isArray() is a built-in JavaScript method that checks whether a given value is an array or not. It returns true if the input is an array, and false otherwise.

let numbers = [1, 2, 3, 4, 5];
let text = 'Hello, world!';

console.log(Array.isArray(numbers)); // Output: true
console.log(Array.isArray(text)); // Output: false

Why Spread Operator?

// Without spread operator
let arr1 = [1, 2];
let arr2 = [3, 4];
arr1.push(arr2); // arr1 is now [1, 2, [3, 4]]
// With spread operator
let arr3 = [1, 2];
let arr4 = [3, 4];
arr3.push(...arr4); // arr3 is now [1, 2, 3, 4]

Resources

00:00