JavaScript: How to Remove Duplicate Values from a Array?

JavaScript: How to Remove Duplicate Values from a Array?

Asked on October 31, 2018 in Javascript.
Add Comment


  • 1 Answer(s)

      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.

    For ex:

    <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>
    

    or

      Use the for-of loop instead of for loop to perform this filtration very easily,like this:

    <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>
    
    Answered on October 31, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.