I hope this helps
var twoDimension = [[1], [2], 3, 4, [5]];
var plano = twoDimension.reduce((acc, el) => acc.concat(el), []);
console.log(plano);
Answer from sonEtLumiere on Stack Overflowjavascript - Flatten an array by only one level without using .flat() - Stack Overflow
Flatten a nested array without using the inbuilt flat() method (interview learning)
Best Ways to Deep Flatten Arrays in JavaScript?
Learn how to flatten an array using the Reduce Method
Videos
I hope this helps
var twoDimension = [[1], [2], 3, 4, [5]];
var plano = twoDimension.reduce((acc, el) => acc.concat(el), []);
console.log(plano);
To flatten by a single level only, Array#concat() can be leveraged. It accepts any amount of arguments, so an array can be spread into the function call:
[].concat(...arr)
This avoids any explicit loops. JavaScript handles everything:
function flatten(arr) {
return [].concat(...arr);
}
console.log(flatten([['foo', 'bar'], ['baz', 'qux']]));
// -> ["foo", "bar", "baz", "qux"]
console.log(flatten([[1], [2], 3, 4, [5]]));
// -> [1, 2, 3, 4, 5]
console.log(flatten([false, [true, [false]], [true]]));
// -> [false, true, [false], true]
console.log(flatten([]));
// -> []
In an interview, I was asked to flatten a nested array in JavaScript without using `flat()`.
Under pressure, I got stuck. Later, I realized it wasn’t that hard — I was just overthinking.
Here’s the recursive solution I wrote:
var array = [0, [1, 2, [33, 44]], [4, 5, 6, 7], [7, 8], 90];
var newArr = [];
function getFlatArray(array) {
for (let index = 0; index < array.length; index++) {
if (typeof array[index] === "number") {
newArr.push(array[index]);
} else {
getFlatArray(array[index]);
}
}
}
getFlatArray(array);
console.log(newArr);
(12) [0, 1*,* 2*,* 33*,* 44*,* 4*,* 5*,* 6*,* 7*,* 7*,* 8*,* 90*]*
Flattening arrays with .flat() is simple, but handling deeply nested arrays can be tricky. What’s your go-to approach for deep flattening in JavaScript? I came across this interesting write-up with some techniques: Deep Flatten Arrays in JavaScript. https://www.interviewsvector.com/javascript/deep-flaten
Would love to hear your thoughts or see alternative methods!
Ever wondered how to fatten an array in JavaScript using the reduce method? Check out this tutorial:
https://www.youtube.com/watch?v=wqJchgHQTwo
If you want more practice, check out the full course here:
https://www.udemy.com/course/cracking-the-javascript-coding-interview/?couponCode=03AFBAFA3BF8FF858384