For todays lodash post I have come around to taking a moment to write a quick post about _.reverse. Lodash is a great project, but many of the methods are pretty much just reverences to native methods, and _.reverse is an example of one of these. Also the native array method on which _.reverse is based has excellent backward compatibility, as the method will work on browsers as old as IE 5.5.
So for a basic example of _.reverse I just have a quick code example in which I am just reversing the array by passing the array to _.reverse.
The native Array.reverse works by just calling it off the instance of Array.
That is all there is to it, not must to write about with this one. However there is the matter that _.reverse is a method that will not return a new array, but mutate the existing one that is passed to it. In most cases this does not present a problem, unless for some reason it does, in which case there will be a need to clone the array first, or write a custom reverse method.
So if lodash is part of the stack then there is or course methods like _.clone, _.cloneDeep, _.create, and so forth to work with that can be used to make both shallow, and deep clones of objects including arrays.
So if lodash is there to work with, then it is no problem at all to address the mangle rather than create new nature of _.reverse. If you are going vanilla js style though there are some quick solutions that can help as well.
Its not like writing an reverse method is that hard if it seems like that is what just needs to happen
A solution like this would work on a wide range of platforms, but if you do not care that much about older browsers there are a number of methods than can be used to clone an array before reversing it.
The native Array.from can be used to quickly create a new array from an array.