Logo

How to get all unique values in a JavaScript array?

When working with JavaScript arrays, you’ll often come across the need to remove duplicates and keep only the unique elements. Whether you’re dealing with user inputs, database records, or API responses, maintaining a clean set of unique values helps ensure predictable outcomes in your code. In this blog, we’ll discuss several effective ways to achieve this, delve into performance considerations, and share some tips that might come in handy during coding interviews.

1. Using a Set

One of the most modern and concise methods involves using the built-in Set object, which automatically stores unique values. Then we can convert it back to an array with the spread operator:

const numbers = [1, 2, 3, 2, 4, 1]; const uniqueNumbers = [...new Set(numbers)]; console.log(uniqueNumbers); // [1, 2, 3, 4]
  • Why This Works: A Set ensures all elements are unique. Converting via [...set] transforms it back into an array.
  • Time Complexity: Insertion in a Set is generally O(1) (amortized), making this method efficient for large arrays.

2. Using filter() and indexOf()

Another approach to filter out duplicates is with the higher-order function filter() in combination with indexOf():

const numbers = [1, 2, 3, 2, 4, 1]; const uniqueNumbers = numbers.filter((value, index, arr) => { return arr.indexOf(value) === index; }); console.log(uniqueNumbers); // [1, 2, 3, 4]
  • Explanation: The callback retains only the first occurrence of each value because indexOf(value) returns the first index at which the value appears.
  • Trade-Off: For large arrays, this is less performant than using a Set because each indexOf() call is O(n), resulting in an overall O(n²) complexity in the worst case.

3. Using reduce() and an Auxiliary Object

If you want to control how you aggregate items, consider the reduce() method:

const numbers = [1, 2, 3, 2, 4, 1]; const uniqueNumbers = numbers.reduce((acc, value) => { if (!acc.includes(value)) { acc.push(value); } return acc; }, []); console.log(uniqueNumbers); // [1, 2, 3, 4]
  • Why Use reduce()?: It allows for more complex operations beyond uniqueness. However, using acc.includes(value) also leads to O(n) checks for each item, potentially making it O(n²) for large arrays.

4. Using forEach() or for Loop with an Auxiliary Data Structure

A classic approach is to loop through all elements and track them with an object or map to ensure uniqueness. For example:

const numbers = [1, 2, 3, 2, 4, 1]; const seen = {}; const uniqueNumbers = []; numbers.forEach((num) => { if (!seen[num]) { uniqueNumbers.push(num); seen[num] = true; } }); console.log(uniqueNumbers); // [1, 2, 3, 4]
  • Performance: Checking and setting properties on an object is O(1) on average, making this method efficient (O(n) overall).
  • Key Collisions: In some very rare cases, object key collisions can happen, but for basic usage with strings and numbers, it’s generally safe.

Interview Tips

  1. Discuss Time Complexity:

    • Using a Set(): O(n) on average, a strong approach to highlight.
    • Using filter() + indexOf(): O(n²) in the worst case. Avoid this for large data sets if performance is critical.
  2. Show Off Modern JavaScript Skills: Demonstrating knowledge of ES6 features like sets and the spread operator indicates you keep your coding practices current.

  3. Edge Cases: Mention how you’d handle empty arrays, arrays with different data types (strings, numbers, objects), or extremely large arrays.

Level Up Your Coding Expertise

If you want to not only remove duplicates from arrays but also master crucial JavaScript and data structure skills for coding interviews, check out these specialized courses from DesignGurus.io:

Practice and Get Feedback

  • Mock Interviews: Sign up for a Coding Mock Interview to get personalized feedback from ex-FAANG engineers who understand what it takes to succeed.
  • YouTube Tutorials: Explore the DesignGurus YouTube Channel for more free tips on system design, coding interviews, and best practices.

Final Thoughts

Getting a unique set of values in a JavaScript array is straightforward when you understand the right method for your situation. From leveraging the built-in Set for efficiency to using filter() or reduce() for more control, there’s a method to suit every need. Understanding these approaches—and their respective time complexities—will help you write cleaner, more optimized code and impress potential employers in coding interviews.

Keep practicing, and don’t forget to explore the resources at DesignGurus.io to sharpen your interview skills, refine your system design expertise, and ultimately land the tech role you’ve been aiming for. Happy coding!

CONTRIBUTOR
TechGrind