Get All Unique Values in a Javascript Array (Remove Duplicates)

When working with JavaScript arrays, it is common to encounter situations where you need to remove duplicate values and retrieve only the unique values. In this blog post, we will explore multiple solutions to achieve this in an efficient and concise manner.

Solution 1: Using Set

One of the easiest ways to remove duplicate values from an array is by using the Set object, which only allows unique values. We can convert the array to a Set and then convert it back to an array to get the unique values.


const array = [1, 2, 3, 3, 4, 4, 5];
const uniqueArray = Array.from(new Set(array));

console.log(uniqueArray);

The above code snippet will output:

[1, 2, 3, 4, 5]

Solution 2: Using Filter and IndexOf

Another approach is to use the filter method along with the indexOf method to filter out the duplicate values. We can create a new array and only add the elements that do not already exist in the new array.


const array = [1, 2, 3, 3, 4, 4, 5];
const uniqueArray = array.filter((value, index, self) => {
  return self.indexOf(value) === index;
});

console.log(uniqueArray);

The above code snippet will output the same result as the previous solution:

[1, 2, 3, 4, 5]

Solution 3: Using Reduce

We can also use the reduce method to iterate over the array and build a new array containing only the unique values. We can use the accumulator to keep track of the unique values encountered so far.


const array = [1, 2, 3, 3, 4, 4, 5];
const uniqueArray = array.reduce((accumulator, value) => {
  if (!accumulator.includes(value)) {
    accumulator.push(value);
  }
  return accumulator;
}, []);

console.log(uniqueArray);

Once again, the above code snippet will output the same result:

[1, 2, 3, 4, 5]

These are three different solutions to remove duplicate values and retrieve only the unique values from a JavaScript array. Depending on your specific use case and performance requirements, you can choose the solution that best fits your needs.


Posted

in

, ,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *