Skip to main content

Command Palette

Search for a command to run...

How to Flatten an Array

Updated
1 min read
How to Flatten an Array

Here is the instruction for this coding exercise:

Create a function to flatten an array without using the Array method .flat()

Given an array [1,2,[3,4, [5,6,7], 8], 9, [10, [20], 30]]

The function should return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]

Note in the example array, the number of levels is unspecified, and it can be nested in any way.

Looping through a list and repeating the same operation with different parts should prompt you to use recursion. Below is a decent solution.

const exampleArray = [1,2,[3,4, [5,6,7], 8], 9, [10, [20], 30]];
let flattenArray: number[] = [];
type DeepArray<T> = Array<T | DeepArray<T>>;

const flatten = (numbers: DeepArray<number>): void => {
  for (let num of numbers) {
    if (Array.isArray(num)){
      flatten(num);
    } else {
      flattenArray.push(num);
    }
  }
}

flatten(exampleArray); // [1,2,3,4,5,6,7,8,9,10]

If you want something fancier, use the Array method reduce.

const exampleArray = [1,2,[3,4, [5,6,7], 8], 9, [10, [20], 30]];

type NestedNumberArray = Array<number | NestedNumberArray>;

const flatten = (numbers: NestedNumberArray): NestedNumberArray => {
  return numbers.reduce((accu: NestedNumberArray, num: number | NestedNumberArray) => {
    if (Array.isArray(num)){
      accu = accu.concat(flatten(num));
    } else {
      accu.push(num);
    }
    return accu;
  },[]);
}

flatten(exampleArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]

More from this blog

UI Dev

18 posts