How to Flatten an Array in JavaScript

preview_player
Показать описание
This is a brief run through on how to flatten an array in JavaScript.

In this playlist
Рекомендации по теме
Комментарии
Автор

when you used the concat method, why did you pass in flatten(element)? It seems to work just passing in (element). Can you explain? Thank you!

jkwon-
Автор

flatArray = flatArray.concat(element) this code will also work, we don't need to call the function recursively

deepsarkar
Автор

My code is logging [1, 2, 3, undefined]. Can't figure out why.
here's my code:
const data = [[1, 2], 3, 4[5, [6, 7]]];

function flatten(arr) {
let flatArray = []

arr.forEach(element => {
if (Array.isArray(element)) {
flatArray =
}
else {
flatArray.push(element);
}
});

return flatArray;
}

const newArray = flatten(data);

console.log(newArray);

charlesloehle