How to make JavaScript Array Unique? [4 Methods]


JavaScript

Understanding JavaScript Array Unique: Removing Duplicates from Arrays

In JavaScript, an array is a data structure that can store multiple values of different data types. Sometimes, an array may contain duplicate values that you may want to remove or filter out. This is where the concept of "unique array" comes in.

Unique array refers to the process of removing duplicate elements from an array. This operation can be performed using various techniques and methods available in JavaScript. By removing duplicates, you can simplify your code and make it more efficient. Additionally, it can be helpful in situations where you need to perform calculations or comparisons on the array elements without duplicates affecting the result.

In this context, JavaScript offers a variety of built-in methods and functions to remove duplicates from an array. In this regard, it is essential to have a solid understanding of JavaScript arrays and the different approaches that can be used to make an array unique. This knowledge can help you write better and more efficient code in your JavaScript projects.

 

Method-1: Using the Set Object

The Set object is a built-in JavaScript object that allows you to store unique values of any type, including primitive types like numbers and strings, as well as objects. One way to get unique arrays in JavaScript is to use the Set object. Though the Set object is not an array, we can make use of the spread operator to expand the unique elements within the Set object to create a unique array.

const arr = [1, 2, 2, 3, 3, 4, 5];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr);

Output

[ 1, 2, 3, 4, 5 ]

In the code above, we create an array with duplicate values, and then use the Set object to create a new set with only unique values. Finally, we use the spread operator to convert the set back into an array.

 

Method-2: Using the filter() method

The filter method is a built-in JavaScript method that creates a new array with all elements that pass a certain test. There are two approaches of using the filter() method to get unique arrays in JavaScript - the indexOf() and includes() methods.

Using the indexOf() method, we can filter out the duplicate values from an array:

const arr = [45, 67, 67, 89, 67, 69];
const uniqueArr = arr.filter((element, index, self) => {
    return index === self.indexOf(element);
});
console.log(uniqueArr);

Output

[ 45, 67, 89, 69 ]

In the code above, we use the filter() method to return only the first occurrence of each element in the array. The indexOf() method returns the index of the first occurrence of an element in an array, so we only keep the elements whose index matches the index returned by indexOf().

The includes() method can also be used to achieve the same results:

const arr = [45, 67, 67, 89, 67, 69];
const uniqueArr = arr.filter((elem, index, self) => {
    return self.indexOf(elem) === index && self.includes(elem);
});
console.log(uniqueArr);

Output

[ 45, 67, 89, 69 ]

In the code above, we use the includes() method to check if the current element is already present in the resulting array.

 

Method-3: Using the reduce() method

The reduce() method is a built-in JavaScript method that allows you to reduce an array to a single value. It takes a callback function that is called on each element of the array, and a starting value. We can make use of the reduce() method to make unique arrays in JavaScript by passing a conditional that checks if an element is present within an array adding a new element to the array.

Let’s illustrate the reduce() method using the below example.

const arr = [45, 67, 67, 89, 34, 34, 69];
const uniqueArr = arr.reduce((acc, each) => {
    if (!acc.includes(each)) {
        acc.push(each);
    }
    return acc;
}, []);

console.log(uniqueArr);

Output

[ 45, 67, 89, 34, 69 ]

In the code above, we use the reduce() method to loop through the array and check if each element is already present in the acc array. If it's not present, we add it to the acc array. Finally, we return the acc array as the result.

 

Method-4: Using for loop

A more traditional approach is to use a for loop to iterate through the array and add only the unique elements to a new array.

const myArray = [1, 2, 3, 2, 4, 1, 5];
const uniqueArray = [];
for (let i = 0; i < myArray.length; i++) {
  if (!uniqueArray.includes(myArray[i])) {
    uniqueArray.push(myArray[i]);
  }
}
console.log(uniqueArray); 

The for loop iterates through each element of "myArray" using the loop variable "i", which starts at 0 and increments by 1 until it reaches the length of "myArray". For each element of "myArray", the if statement checks if the current element is already included in "uniqueArray" using the includes() method.

If the element is not included in "uniqueArray", it is added to the array using the push() method. This ensures that only unique elements are added to the "uniqueArray".

Output

[1, 2, 3, 4, 5]

 

Summary

In JavaScript, an array is a data structure that can store multiple values of different data types. Sometimes, an array may contain duplicate values that you may want to remove or filter out. This is where the concept of "array unique" comes in.

To make a JavaScript array unique, you can use various techniques and methods available in JavaScript. Some of these methods include using the Set object, the filter() method, the reduce() method, or a for loop. These methods can help you simplify your code, make it more efficient, and improve the performance of your JavaScript projects.

Using the Set object is one of the easiest ways to make an array unique, as it automatically removes duplicates. You can then convert it back to an array using the spread operator. Another approach is to use the filter() method or the reduce() method to create a new array that only includes the unique elements of the original array. You can also use a for loop to iterate through the array and add only the unique elements to a new array.

 

References

Set - JavaScript | MDN (mozilla.org)
Array.prototype.filter() - JavaScript | MDN (mozilla.org)
Array.prototype.reduce() - JavaScript | MDN (mozilla.org)

 

Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment