The question is to output an array of unique elements from the given array with duplicates.

As I know, we can do this in 2 ways in JavaScript. One way is by using default Array methods, and the other is by using ES 6 feature.

First, let us see by using the default method.

In this, we are going to use the array filter method. This approach filters and returns the unique element when it satisfies a condition. Let us see the code.

    // Given array with duplicates
    let array_1 = ["Red", "Yellow", "Blue", "Yellow", "Black", "Red", "White"]
    
    // Unique array 
    let u_array = () => {
       return array_1.filter( (item, position) => {
            return array_1.indexOf(item) == position
       })
    } 
    console.log(u_array())

In the array filter method, we pass two parameters, 1. the element as the item and 2. it’s position.
Each iteration will return the element if the item’s index is equal to the position. If not, it won’t.

Iteration 0 : Item: Red, Position: 0 – return element
Iteration 1 : Item: Yellow, Position: 1 – return element
Iteration 2 : Item: Blue, Position: 2 – return element
Iteration 3 : Item: Yellow, Position: 3 – won’t return
Iteration 4 : Item: Black, Position: 4 – return element
Iteration 5 : Item: Red, Position: 5 – won’t return
Iteration 6 : Item: White, Position: 6 – return element

Now with ES6, you can apply the Set method on the given array, which returns an array with unique elements,

    // Given array with duplicates
    let array_1 = ["Red", "Yellow", "Blue", "Yellow", "Black", "Red", "White"]
    
    // Unique array 
    let u_array = () => {
        return [...new Set(array_1)]
    }
    console.log(u_array())

0 Comments

Submit a Comment

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