JavaScript Question: How Can I Flatten an Array?

preview_player
Показать описание
How can you take an Array of Arrays and flatten it so that it is a single array without sub-arrays and just with elements. In this tutorial we are going to look at how to do that.

Would you like to help keep this channel going?

Tutorials referred to in this video:

For more resources on JavaScript:

#javascript #AllThingsJavaScriptLLC
Рекомендации по теме
Комментарии
Автор

arry.toString() is pretty nifty, i.e. if you are not allowed to use flat(). Then, split the string, convert to number and push into new array.

Petar_Ral
Автор

I am Surprised No one taught about flat(Infinity)
Eg - arr = [1, 2, 5, 6, [3, 8, 7, 4], 56, 72, [23, 21, [43, 53], 67], 100, 200, 300, ];
newArry = arr.flat(Infinity);
console.log(newArry);

Kirankumar-qnzf
Автор

loads has a flattenDeep method which works well too

mudandmoss
Автор

*A better recursive solution | Easy to understand*

let arr = [1, 2, [4, 3, [5, 6, 7, [8]]], 9, [10]];
let out = [];

let flatenArr = (arr) => {
arr.forEach((ele) => {
if (Array.isArray(ele)) flatenArr(ele);
else out.push(ele);
});
};

flatenArr(arr);
console.log(out);

subham-raj