ArticleZip > How To Get An Array Of Unique Values From An Array Containing Duplicates In Javascript Duplicate

How To Get An Array Of Unique Values From An Array Containing Duplicates In Javascript Duplicate

Dealing with duplicates in an array is a common challenge in JavaScript coding. If you've ever found yourself in a situation where you need to extract unique values from an array that contains duplicates, you're in the right place. In this article, we'll walk through the steps to get an array of unique values efficiently.

To start off, let's define an example array that contains duplicate values:

Javascript

const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];

One simple approach to obtaining an array of unique values is by using the `Set` object in JavaScript. The `Set` object lets you store unique values of any type. Here's how you can use a `Set` to eliminate duplicates from the array:

Javascript

const uniqueValues = [...new Set(arrayWithDuplicates)];
console.log(uniqueValues); // Output: [1, 2, 3, 4, 5]

In this code snippet, the `new Set(arrayWithDuplicates)` creates a set containing the unique values from the original array. By spreading the set into a new array using `...`, we obtain the final array of unique values stored in the `uniqueValues` variable.

Another method to achieve the same result is by using the `filter()` method in combination with the `indexOf()` method:

Javascript

const uniqueValues = arrayWithDuplicates.filter((value, index, array) => array.indexOf(value) === index);
console.log(uniqueValues); // Output: [1, 2, 3, 4, 5]

In this snippet, the `filter()` method iterates over each element in the array and only keeps the elements whose first occurrence (index) is equal to the current index being processed. This effectively removes duplicates, resulting in an array of unique values.

If you prefer a more concise way to remove duplicates using the ES6 `reduce()` method:

Javascript

const uniqueValues = arrayWithDuplicates.reduce((acc, currentValue) => {
    if (!acc.includes(currentValue)) {
        acc.push(currentValue);
    }
    return acc;
}, []);
console.log(uniqueValues); // Output: [1, 2, 3, 4, 5]

In this code snippet, the `reduce()` method accumulates unique values by checking if the current value is not already in the accumulator array. If not, it gets added to the accumulator, resulting in a final array of unique values.

In conclusion, when dealing with arrays containing duplicate values in JavaScript, there are multiple efficient strategies for obtaining an array of unique values. Whether you choose to use `Set`, `filter()`, or `reduce()`, these methods provide you with the tools necessary to streamline your code and achieve the desired outcome effortlessly.

×