Q:

How to Remove Duplicate Values from a JavaScript Array

0

How to Remove Duplicate Values from a JavaScript Array

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the indexOf() Method

You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.

Let's take a look at the following example to understand how it basically works:

<script>
    // Defining function to get unique values from an array
    function getUnique(array){
        var uniqueArray = [];
        
        // Loop through array values
        for(i=0; i < array.length; i++){
            if(uniqueArray.indexOf(array[i]) === -1) {
                uniqueArray.push(array[i]);
            }
        }
        return uniqueArray;
    }
    
    var names = ["John", "Peter", "Clark", "Harry", "John", "Alice"];
    var uniqueNames = getUnique(names);
    console.log(uniqueNames); // Prints: ["John", "Peter", "Clark", "Harry", "Alice"]
</script>

Alternatively, you can use the newly introduced ES6 for-of loop instead of for loop to perform this filtration very easily, as demonstrated in the following example:

<script>
    // Defining function to get unique values from an array
    function getUnique(array){
        var uniqueArray = [];
        
        // Loop through array values
        for(var value of array){
            if(uniqueArray.indexOf(value) === -1){
                uniqueArray.push(value);
            }
        }
        return uniqueArray;
    }
    
    var names = ["John", "Peter", "Clark", "Harry", "John", "Alice"];
    var uniqueNames = getUnique(names);
    console.log(uniqueNames); // Prints: ["John", "Peter", "Clark", "Harry", "Alice"]
</script>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Remove a Property from a JavaScript Object... >>
<< How to Encode URL in JavaScript...