Recursively flatten an array or arrays.
npx @tessl/cli install tessl/npm-arr-flatten@1.1.0arr-flatten provides a high-performance recursive array flattening utility that converts nested arrays into a single flat array. It offers a simple, focused API with minimal overhead, making it suitable for performance-critical applications that need to process nested array structures.
npm install arr-flattenvar flatten = require('arr-flatten');For ES6 modules (with transpilation):
import flatten from 'arr-flatten';var flatten = require('arr-flatten');
// Simple nested array
flatten(['a', ['b', ['c']], 'd', ['e']]);
//=> ['a', 'b', 'c', 'd', 'e']
// Deeply nested array
flatten(['a', [[[[[[[['b', [['c']]]]]], 'd', ['e']]]]]]);
//=> ['a', 'b', 'c', 'd', 'e']
// Mixed content types
flatten([1, [2, [3, 4]], 5]);
//=> [1, 2, 3, 4, 5]Recursively flattens an array of arbitrary nesting depth into a single flat array while preserving element order.
/**
* Recursively flatten an array or arrays
* @param {Array} arr - The array to flatten, may contain nested arrays at any depth
* @returns {Array} A new flattened array containing all elements from nested structures
*/
function flatten(arr)Parameters:
arr (Array): The input array to flatten. Can contain nested arrays at any depth along with primitive values.Returns:
Behavior:
Usage Examples:
var flatten = require('arr-flatten');
// Basic flattening
var result = flatten([1, [2, 3], 4]);
console.log(result); // [1, 2, 3, 4]
// Deep nesting
var deep = flatten([1, [2, [3, [4, [5]]]]]);
console.log(deep); // [1, 2, 3, 4, 5]
// Mixed types
var mixed = flatten(['hello', [42, ['world', true]], null]);
console.log(mixed); // ['hello', 42, 'world', true, null]
// Empty arrays
var withEmpty = flatten([1, [], [2, []], 3]);
console.log(withEmpty); // [1, 2, 3]Performance Characteristics:
Error Handling:
.length property and iterate