Description: Write a function named flatten that accepts an array and merge them in a single array
flatten([1, 2, 3]) // [1, 2, 3]
flatten([1, 2, [1, 2], [1, 3], 6]) // [1, 2, 1, 2, 1, 3, 6]
flatten([1, [2, [3, [4]], 5], 6]) // [1, 2, 3, 4, 5, 6]
flat()
One layer:
const arr = [0, 1, 2, [3, 4]];
console.log(arr.flat());
// flat() = flat(1)
// [0, 1, 2, 3, 4]
Two layers:
const arr = [1, 2, [3, 4, [5, 6]]];
console.log(arr.flat(2));
// [ 1, 2, 3, 4, 5, 6 ]
Many layers:
const arr = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
concat()
One layer works only
const arr = [1, 2, [3, 4]];
const newArray = [].concat(...arr);
console.log(newArray);
// output: [ 1, 2, 3, 4 ]
isArray()
function flatten(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
let flatArr = flatten(arr[i]);
for (let j = 0; j < flatArr.length; j++) {
result.push(flatArr[j]);
}
} else {
result.push(arr[i]);
}
}
return result;
}
console.log(flatten([1, 2, [1, 2], [1, 3], 6]));
Reference: Array.prototype.flat()