LoginSignup
2
1

More than 5 years have passed since last update.

Flatten an array in TypeScript

Posted at

An array containing primitive values, objects and other arrays can be flattened using a recursive reduce function.

const flatten = < T = any > (arr: T[]) => {
  const reducer = < T = any > (prev: T[], curr: T | T[]) => {
    if (curr.constructor !== Array) {
      return [...prev, curr];
    }
    return curr.reduce(reducer, prev);
  };
  return arr.reduce(reducer, []);
};

For example:

const values = [1, 2, 3, 4, [5, 6], 7, [8, [9]]];
const flatValues = flatten(values);
console.log(flatValues);
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]

Github Gist

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1