Web development and Tech news Blog site. WEBISFREE.com

HOME > lodash

Exploring the Lodash Method uniq()

Last Modified : 04 Oct, 2023 / Created : 04 Oct, 2023
219
View Count

We will explore the uniq() method from lodash which can leave only unique values in an array.

_.uniq(data)

The simple syntax is as shown above. Then, when and how should we use the uniq() method?



# Removing Duplicates with lodash uniq()


Lodash's uniq() can remove duplicate values from an array. Therefore, if there is an array with multiple identical values and you need to simply remove unnecessary duplicate data, you can use lodash's uniq().

Below is a simple example.


! Example of lodash uniq()

Below, there is an array, myArray, that contains seven numbers.
myArray = [ 1, 2, 3, 3, 3, 4, 5];

As you can see from the variable values, myArray has three duplicate values of 3. If you want to remove the duplicates? Proceed as follows.
newArray = _.uniq(myArray);

// Result
[1, 2, 3, 4, 5]

As you can see, the seven values are reduced to five. Additionally, the duplicates, the number 3, were all removed easily. In this way, you can easily eliminate duplicate values and retain only the unique ones.


So far, we have explored the uniq() method among lodash methods.
Perhaps you're looking for the following text as well?

    Previous

    Merge with unique values using lodash union method

    Previous

    [Lodash] thru() Method information and examples