UNPKG

diginext-utils

Version:
33 lines 848 B
/** * Flattens a nested array by one or more levels. * * @template T - The type of elements in the array * @param array - The array to flatten * @param depth - The depth level to flatten (default: 1) * @returns A new flattened array * * @example * ```ts * flatten([1, [2, 3], [4, 5]]); // [1, 2, 3, 4, 5] * flatten([1, [2, [3, [4]]]], 2); // [1, 2, 3, [4]] * flatten([1, [2, [3, [4]]]], Infinity); // [1, 2, 3, 4] * ``` */ export function flatten(array, depth = 1) { if (!Array.isArray(array)) { return []; } if (depth <= 0) { return array; } return array.reduce((acc, item) => { if (Array.isArray(item)) { acc.push(...flatten(item, depth - 1)); } else { acc.push(item); } return acc; }, []); } //# sourceMappingURL=flatten.js.map