JS Coding Question #4: Remove Duplicates [Common Question]
Let's Code

Let's Code @frontendengineer

About: A fan of technology/innovation, software engineer, and a father.

Joined:
May 6, 2019

JS Coding Question #4: Remove Duplicates [Common Question]

Publish Date: Aug 29 '21
18 2

Interview Question #4:

Write a function that will remove duplicate in an array❓🤔 You can get a variation of this question as Get unique characters from a list.

If you need practice, try to solve this on your own. I have included 2 potential solutions below.

Note: There are many other potential solutions to this problem.

Feel free to bookmark 🔖 even if you don't need this for now. You may need to refresh/review down the road when it is time for you to look for a new role.

Code: https://codepen.io/angelo_jin/pen/PojPRzQ

Solution #1: ES6 Set

  • uses the elegance of Set just like other programming languages. A value in the Set may only occur once; it is unique in the Set's collection.
function removeDuplicates(array) {
  return [...new Set(array)]
}
Enter fullscreen mode Exit fullscreen mode

Solution #2: Object

  • below will use a js plain object to store key value pairs. Value can be other values as well, i chose to increment it so we may use it for other purpose like get the total count for a characters, etc.
function removeDuplicates(array) {
  const map = {}

  for (const char of array) {
    if (map[char]) {
      map[char]++
    } else {
       map[char] = 1
    }
  }

  return Object.keys(map)
}
Enter fullscreen mode Exit fullscreen mode

Happy coding and good luck if you are interviewing!

If you want to support me - Buy Me A Coffee

In case you like a video instead of bunch of code 👍😊

Comments 2 total

  • Matin
    MatinApr 20, 2023

    Hi, great solutions! I think the question could be more clear 😁 since this code doesn't remove the duplicates!!! it just creates a new array but without the duplicates!!!!

    Thanks anyways for these JS questions, they make me think more methodically!!

    • Let's Code
      Let's CodeMay 4, 2023

      you are welcome! Creating new array typically an engineer would want to prevent unexpected side effects or bugs.

Add comment