ArticleZip > How To Remove Elements From Array Duplicate

How To Remove Elements From Array Duplicate

Arrays are fundamental in programming, allowing you to store multiple values within a single variable. Occasionally, you may encounter a situation where you need to remove duplicates from an array to work with unique elements only. In this article, we will explore how to efficiently remove duplicate elements from an array in various programming languages.

In JavaScript, a common approach to remove duplicates from an array is by leveraging the `Set` object. The `Set` object allows you to store unique values of any type, including primitive types and object references. By creating a new `Set` from an existing array and converting it back to an array using the spread operator `...`, you eliminate duplicate elements effortlessly.

Here is an example of how to remove duplicates from an array in JavaScript using the `Set` object:

Javascript

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

In Python, you can achieve a similar result using the versatile `set()` function. By converting the array into a set, which only stores unique elements, and then back to a list, you effectively remove duplicates from the array.

Here is how you can remove duplicate elements from an array in Python:

Python

arr = [1, 2, 3, 3, 4, 5, 5]
unique_arr = list(set(arr))
print(unique_arr)  # Output: [1, 2, 3, 4, 5]

If you are working with languages like Java or C++, where sets are not readily available, you can iterate through the array and build a new array with unique elements. This method involves checking whether each element is already present in the new array before adding it, ensuring only distinct values are included.

Here is a generic example of removing duplicates from an array in Java:

Java

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Integer[] arr = {1, 2, 3, 3, 4, 5, 5};
        Set set = new HashSet();
        List uniqueArr = new ArrayList();
        
        for (Integer num : arr) {
            if (set.add(num)) {
                uniqueArr.add(num);
            }
        }
        
        System.out.println(uniqueArr); // Output: [1, 2, 3, 4, 5]
    }
}

By following these examples, you can efficiently remove duplicate elements from an array in different programming languages, ensuring your data is clean and optimized for further processing. Remember to choose the method that best suits your programming environment and requirements.