flatten([1, 'any [complex] string', null, function() {}, [1, 2, [3, '4'], 0], [], { a: 1 }]);
// возвращает
// [1, 'any [complex] string', null, function() {}, 1, 2, 3, '4', 0, { a: 1 }]
function flatten(list) {
console.log(flatten)
}
const flatten = arr => [].concat(...arr.map(n => Array.isArray(n) ? flatten(n) : n));
// или
function flatten(arr) {
const result = [];
for (const n of arr) {
if (n?.constructor === Array) {
[].push.apply(result, flatten(n));
} else {
result.push(n);
}
}
return result;
}
function flatten(arr) {
const result = [];
const stack = [];
for (let i = 0; i < arr.length || stack.length; i++) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else if (arr[i] instanceof Array) {
stack.push([ i, arr ]);
[ i, arr ] = [ -1, arr[i] ];
} else {
result.push(arr[i]);
}
}
return result;
}
// или
function flatten([...arr]) {
for (let i = 0; i < arr.length; i++) {
const n = arr[i];
if (n?.[Symbol.iterator] && typeof n !== 'string') {
arr.splice(i--, 1, ...n);
}
}
return arr;
}