top of page

Get Unique Values from Array JavaScript using Set

Writer's picture: CODING Z2MCODING Z2M
Get Unique Values from Array JavaScript using Set

Extracting Unique Values from an Array in JavaScript

Get Unique Values from Array JavaScript using Set: In programming, managing data efficiently is crucial to writing effective code. JavaScript, a powerful and flexible language, empowers developers to handle arrays with ease. A frequent task developers face involves extracting unique values from an array. In this guide, we will explore how to extract unique values from an array in JavaScript.


Understanding Arrays in JavaScript


Arrays are fundamental data structures in JavaScript, allowing storage of multiple values under a single variable. They can hold different data types, including numbers, strings, and even other arrays.


When working with arrays, it is often necessary to ensure that the values are unique. For instance, unique values can be crucial for creating searchable lists, filtering data, or calculating averages without the impact of duplicate entries.


Get Unique Values from Array JavaScript using Set

Basic Approach: Using the `Set` Object


One of the simplest methods to extract unique values from an array is using the `Set` object, introduced in ES6 (ECMAScript 2015). A `Set` only stores unique values.


Example Code

const array = [1, 2, 3, 1, 2, 4, 5];
const uniqueValues = [...new Set(array)];
console.log(uniqueValues); // Output: [1, 2, 3, 4, 5]

Explanation


In the above code, `Set` is created from the original array. The spread operator (`...`) then converts the `Set` back into an array. This method is efficient and concise, making it a popular choice for retrieving unique values. When benchmarked, using a `Set` can outperform filtering methods, especially when handling arrays with thousands of elements.

Get Unique Values from Array JavaScript using Set - Magic One-Liner Example:

const categories = [...new Set(expenses.map((expense) => expense.category))];

This concise piece of code combines several powerful JavaScript features to get the job done. Let’s break it down step by step! Step 1: Extracting Categories with map()

The .map() method creates a new array by extracting the category from each object in the array.

const expenses = [
  { id: 1, category: "Food" },
  { id: 2, category: "Transport" },
  { id: 3, category: "Food" },
  { id: 4, category: "Entertainment" }
];
const categoriesList = expenses.map((expense) => expense.category);
console.log(categoriesList);

Output:

["Food", "Transport", "Food", "Entertainment"]

As you can see, duplicates are included, which brings us to the next step! Step 2: Removing Duplicates with Set()

A Set is a built-in JavaScript object that automatically removes duplicate values. Wrapping the categoriesList array in new Set() will filter out the duplicates for us.

new Set(["Food", "Transport", "Food", "Entertainment"]);

Output:

new Set(["Food", "Transport", "Entertainment"]);

Only unique values remain! But a Set is not an array, so we need one more step.

Step 3: Converting Set Back to an Array The Set returns an object, not an array. To convert it back, we use the spread operator (...), which expands elements of the Set and places them inside a new array.

const categoriesList = [...new Set(["Food", "Transport", "Food", "Entertainment"])]
console.log(categoriesList);

Output:

["Food", "Transport", "Entertainment"]

And just like that, we have a clean array of unique category names!


One-Liner Recap:

const categories = [...new Set(expenses.map((expense) => expense.category))];
  • map() → Extracts category names

  • Set() → Removes duplicates

  • ... (spread) → Converts the Set back to an array

Simple yet powerful!


Get Unique Values from Array JavaScript using Set

Final Thoughts


Extracting unique values from an array in JavaScript doesn't have to be a complicated task. With the powerful combination of map(), Set(), and the spread operator (...), you can achieve clean and efficient code in just one line. Whether you're building dropdowns, filtering data, or optimizing your application's performance, this method offers both simplicity and effectiveness.

Comments


bottom of page