Functional Programming in JavaScript: Understanding How to Extract Unique Values from an Array
Hey HaWkers! How's it going?!
Suppose you have a data set with multiple repeated values in an Array, and you need to extract only unique values. But how to do it? Don't worry, this task can be easily done with the help of the Spread
operator and the Set
object, and that's exactly what we're going to talk about in this post.
What are unique values in an Array?
Unique values in an Array are those that appear only once, that is, they do not repeat. Duplicated values, on the other hand, appear more than once in the Array. For example, consider the following Array:
const array = [1, 2, 3, 3, 4, 5, 5, 5, 6];
The unique values in this Array are: 1
, 2
, 4
, and 6
. The duplicated values are: 3
and 5
.
How to extract unique values from an Array with JavaScript?
To extract unique values from an Array in JavaScript, we can use the Spread
operator and the Set
object. See the example below:
const array = [1, 2, 3, 3, 4, 5, 5, 5, 6];const uniqueArray = [...new Set(array)];console.log(uniqueArray);// [1, 2, 3, 4, 5, 6]
In this example, we are creating a new Set
object from the original Array using the Spread
operator, and then creating a new Array from the Set
object again using the Spread
operator. The Set
object is a collection of unique values, which means it does not allow duplicated values. By converting the Set
object back to an Array, we are getting only the unique values from the original Array.
In the example above, the uniqueArray
contains the unique values from the original Array array
.
Final Considerations
Using the Spread
operator and the Set
object is an easy and fast way to extract unique values from an Array in JavaScript. However, it is important to remember that this approach works only with Strings and numbers. If your Array contains objects or other types of data, you need to create a custom function to extract unique values.
I hope this post has been helpful to you. If you have any questions or suggestions, please send me a direct message on Instagram.
And if you have already used the Spread
operator and the Set
object to extract unique values from an Array before, share your experience with me there too!