I have an array like the following: var arr = ['one', 'two', ['three', 'four']];
While trying to return each element by using the arrow function, it returns undefined
as the third element, instead of the elements values. I've attempted to restructure it, but none of then return all the elements of both arrays. I could use a for loop, do the logic to push each element, but I want to understand and learn how to use arrow functions for cases like this.
arr.map(e => {
if(typeof(e) == "object"){
e.map(t => t)
} else{ return e; }
})
Will really appreciate some clarification in this matter. The expected result is an array like the following: ['one', 'two', 'three', 'four'].
Array.prototype.map()
is not designed and implemented to flatten an array. Even if .map()
did flatten an array e.map(t => t)
is not return
ed from .map()
callback function at the code at the question.
arr.map(e => {
if(typeof(e) == "object"){
e.map(t => t) // no value is `return`ed here
} else{ return e; }
})
There are a variety of approaches and Array
methods that can be used to flatten an Array
, including .flat()
, .flatMap()
and .concat()
, e.g., see Merge/flatten an array of arrays in JavaScript?