Login

Remove Duplicates from an Array

Write a function that removes duplicate elements from an array.

Advanced


Instructions

Write a function that receives an array of numbers and returns an array with the duplicate elements removed.

For example, if the input is [1,2,3,1,2,3], the output should be [1,2,3].

Tests
0/4
Function Call:
Expected:
removeDuplicates([1,2,3])
[ 1, 2, 3 ]
Run test

removeDuplicates([1,1,1,1])
[ 1 ]
Run test

removeDuplicates([])
[]
Run test

Hidden Test
?
Run test

See Solution
const removeDuplicates = (myArray) => {
   return Array.from(new Set(myArray))
}

Explanation

  • We use the Set object to store unique values of any type.
  • We then convert the Set object to an array using the Array.from method.

Complexity Analysis

The time complexity for this solution is O(n) where n is the length of the input array.

Alternative

For loop

function removeDuplicates(myArray) {
      let uniqueArray = [];
      for (let i = 0; i < myArray.length; i++) {
         if (uniqueArray.indexOf(myArray[i]) === -1) {
               uniqueArray.push(myArray[i]);
         }
      }
      return uniqueArray;
}

Spreading

function removeDuplicates(myArray) {
    return [...new Set(myArray)];
}
Any improvement idea? Share with us!