Cara Memperbaiki Array di JavaScript secara rekursif
const arrToFlat = [1, [2, [[3, 4], 5], 6]];
function flatArray(arr) {
return arr.reduce((flat, toFlatten) => flat.concat(
Array.isArray(toFlatten) ? flatArray(toFlatten) : toFlatten), []);
}
function flatArrayIter(arr) {
const tempArr = [...arr];
const flat = [];
while (tempArr.length) {
const next = tempArr.pop();
Array.isArray(next) ? tempArr.push(...next) : flat.push(next);
}
return flat.reverse();
}
Kasettado