Write a function to flatten a nested array, so that all nested arrays are merged into a single array with all elements at the same level.
Input: nestedArray = [1, 4, 5, [5, 6, 8, [4, 56]]]
Output: [1, 4, 5, 5, 6, 8, 4, 56]
Input: nestedArray = [1 , 2 , [{"name":"John"}, 6]]
Output: [1 , 2 , {"name":"John"}, 6]
function method1(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
const element = arr[i];
if (Array.isArray(element)) {
newArr.push(...method1(element));
} else {
newArr.push(element);
}
}
return newArr;
}
const nestedArray1 = [1, 4, 5, [5, 6, 8, [4, 56]]];
method1(nestedArray1); //output: [1, 4, 5, 5, 6, 8, 4, 56]
const nestedArray2 = [1 , 2 , [{"name":"John"}, 6]];
method1(nestedArray2); //output: [1 , 2 , {"name":"John"}, 6]
function flattenArrayFlat(arr) {
return arr.flat(Infinity); // Infinity ensures all levels are flattened
}
const nestedArray1 = [1, 4, 5, [5, 6, 8, [4, 56]]];
flattenArrayFlat(nestedArray1); //output: [1, 4, 5, 5, 6, 8, 4, 56]
const nestedArray2 = [1 , 2 , [{"name":"John"}, 6]];
flattenArrayFlat(nestedArray2); //output: [1 , 2 , {"name":"John"}, 6]
function flattenArrayReduce(arr) {
return arr.reduce((acc, val) => {
return acc.concat(Array.isArray(val) ? flattenArrayReduce(val) : val);
}, []);
}
const nestedArray1 = [1, 4, 5, [5, 6, 8, [4, 56]]];
flattenArrayReduce(nestedArray1); //output: [1, 4, 5, 5, 6, 8, 4, 56]
const nestedArray2 = [1 , 2 , [{"name":"John"}, 6]];
flattenArrayReduce(nestedArray2); //output: [1 , 2 , {"name":"John"}, 6]
function flattenArrayStack(arr) {
const stack = [...arr];
const result = [];
while (stack.length > 0) {
const item = stack.pop();
if (Array.isArray(item)) {
stack.push(...item);
} else {
result.push(item);
}
}
return result.reverse(); // Reverse to restore original order
}
const nestedArray1 = [1, 4, 5, [5, 6, 8, [4, 56]]];
flattenArrayStack(nestedArray1); //output: [1, 4, 5, 5, 6, 8, 4, 56]
const nestedArray2 = [1 , 2 , [{"name":"John"}, 6]];
flattenArrayStack(nestedArray2); //output: [1 , 2 , {"name":"John"}, 6]
function* flattenArrayGenerator(arr) {
for (const item of arr) {
if (Array.isArray(item)) {
yield* flattenArrayGenerator(item);
} else {
yield item;
}
}
}
function getFlattenedArray(arr) {
return [...flattenArrayGenerator(arr)];
}
const nestedArray1 = [1, 4, 5, [5, 6, 8, [4, 56]]];
getFlattenedArray(nestedArray1); //output: [1, 4, 5, 5, 6, 8, 4, 56]
const nestedArray2 = [1 , 2 , [{"name":"John"}, 6]];
getFlattenedArray(nestedArray2); //output: [1 , 2 , {"name":"John"}, 6]
function flattenArrayForEach(arr) {
const result = [];
arr.forEach(item => {
if (Array.isArray(item)) {
result.push(...flattenArrayForEach(item));
} else {
result.push(item);
}
});
return result;
}
const nestedArray1 = [1, 4, 5, [5, 6, 8, [4, 56]]];
flattenArrayForEach(nestedArray1); //output: [1, 4, 5, 5, 6, 8, 4, 56]
const nestedArray2 = [1 , 2 , [{"name":"John"}, 6]];
flattenArrayForEach(nestedArray2); //output: [1 , 2 , {"name":"John"}, 6]