> Please someone explain me how this snippet is actually work ?
var arr = [1, 2, [3, 4, [5, 6]]];
// to enable deep level flatten use recursion with reduce and concat
function flatDeep(arr, d = 1) {
return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
: arr.slice();
};
flatDeep(arr, Infinity);
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.
This looks like a solution from the guide, and it was written more to be clever than useful. Of course as usefulness goes, flattening a deeply-nested array with arbitrary elements is a problem you’ll never see in real life. If you’re not already familiar with how .reduce() works, you may want to experiment with it for a while; it’s pretty hard to explain it in the context of an obfuscated answer.