Remove duplicate items from an array with a custom function in JavaScript


In this problem statement our aim is to write an algorithm to remove duplicate items from an array with a function with the help of Javascript functionalities.

Understanding the problem statement

In the above problem statement we have to create a function by which we can accept an array as a parameter and give a new array to store the unique items from the given input array and without including the identical values. For example - suppose we have an array as [0, 0, 2, 2, 3, 3] so after removing the duplicate numbers we will have a new array as [0, 2, 3].

Logic for the given problem

The algorithm will be provided to iterate over the elements in the input array and then we will have to add the items into a newly created array of unique items if the item has not yet been added. We will use the map function of Javascript to provide effective time complexity.

Algorithm

Step 1: Define a function to remove the duplicate numbers from an array and return a new array of unique elements as output.

Step 2: For storing the new array of unique elements of the input array as a result array.

Step 3: We will use the map method to store the items we have seen previously in the array.

Step 4: Use a for loop to iterate through the input array items.

Step 5: Check the condition if the array item has been seen before or not. If it is seen then set it as true and push all the unique items in the result array.

Example

//function to extract the duplicate items from the array
function removeDuplicateItems(array) {
  var result = [];
  var saw= new Map();
  for (let i = 0; i < array.length; i++) {
   if (!saw.has(array[i])) {
     saw.set(array[i], true);
     result.push(array[i]);
   }
  }
  return result;
}

const array = [11, 21, 21, 31, 41, 41, 51];
console.log(removeDuplicateItems(array));

Output

[ 11, 21, 31, 41, 51 ]

Complexity

The time taken by the algorithm is O(n) where n is the length of the input array. Because we have traversed the array items to check the duplicate items in the array.

Conclusion

In the above function we have implemented a code for removing the same items from an array. This task can be achieved with O(n) time complexity depending upon the size of the arrays.

Updated on: 16-Aug-2023

289 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements