Open In App

How to use the Reverse method in Lodash ?

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Reverse method in Lodash is the go-to function for quickly reversing arrays or strings, offering a convenient and efficient way to manipulate data structures in JavaScript.

The below approaches will explain how you can use the reverse method in Lodash.

Run the below command before running the below codes in your local:

npm i lodash

Using the reverse() method to reverse an array

In this approach, we are using Lodash’s reverse method directly on an array to reverse its elements, modifying the original array, and the res variable will store the reversed array.

Syntax:

_.reverse(array)

Example: The below example uses the lodash’s reverse() method to reverse an array.

JavaScript
const _ = require('lodash');
const arr = [1, 2, 3, 4, 5];
const res = _.reverse(arr);
console.log(res);

Output:

[ 5, 4, 3, 2, 1 ]

Using the reverse() method to reverse a string

In this approach, we are using Lodash’s reverse method along with split(”) to convert the string str into an array of characters, then join(”) combines the reversed array back into a string, stored in res, which is then logged to the console.

Syntax:

_.reverse(str.split('')).join('')

Example: The below example uses a reverse() method to Reverse a String.

JavaScript
const _ = require('lodash');
const str = 'Hello, GeeksforGeeks!';
const res = _.reverse(str.split('')).join('');
console.log(res); 

Output:

!skeeGrofskeeG,olleH

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads