// Created on savesnippets.com ยท https://savesnippets.com/E0ckac5UnLuEd0 const flatDeep = (arr, depth = Infinity) => arr.flat(depth); // Manual fallback for environments without Array.flat: function flatDeepManual(arr, depth = Infinity) { return depth > 0 ? arr.reduce( (acc, val) => acc.concat(Array.isArray(val) ? flatDeepManual(val, depth - 1) : val), [] ) : arr.slice(); } // Usage const nested = [1, [2, [3, [4, [5]]]]]; console.log(flatDeep(nested)); // [1, 2, 3, 4, 5] console.log(flatDeep(nested, 2)); // [1, 2, 3, [4, [5]]]