lodash flatmap method and alternatives
However there are many methods that I might use other than reduce including methods like the lodash flatten method, and the lodash chunk methods that are helpful tools when it comes to working with multidimensional arrays. With lodash there are a few methods that are a single method that combines the functionality of two methods such as the lodash flatmap method which I will be going over in this post.
So the lodash flatmap method in lodash is one of many methods that I do not use often, and alo it is not such a big deal to just use map, and then flatten. never the less this will be the subject of this post.
1 - Lodash flat map and other lodash methods
1.1 - lodash flatmap basic example
The lodash flat map method works more or less the same way as the lodash map method in the sense that the first argument is a collection and the second argument is an iteratee method for each element in the collection. The difference is that an array of results for each element is what is expected to be returned by the iteratee and that array is to be flattened into an array of just one dimension.
1.2 - Chaining lodash map and flatten
To some extent the lodash flatten method is redundant as the same result can be achieved with the lodash map and lodash flatten methods by way of chaining. There are two ways of going about doing chaining with lodash, one of which is to call the lodash chain method and the other is to call the main lodash method. When calling one or the other I start out by passing the value that I want to chain with, what is returned is then an object to which I can call all kinds of lodash methods such as the lodash map and flatten methods. In order to get a final value when doing this I then need to call a lodash method that will return a primitive value, or call the value method of the object wrapper.
2.1 - Array map, reduce, and concat chain
Maybe one of the best options to go with these days will still involve chaining a few native method that include array map, along with array reduce and array concat.
This solution might still break on older browsers, but often so will lodash code as well in some cases it it is a late version of lodash.
2.2 - Native array flat method
3 - Conclusion