karasms.com

Unique Values Extraction from Object Arrays in JavaScript

Written on

Chapter 1: Introduction to Unique Values in Arrays

In a prior discussion titled “Three Easy Ways to Remove Duplicate Array Values in JavaScript,” we explored various algorithms aimed at generating an array containing distinct values. A frequent inquiry stemming from that article was how to derive unique values based on a specific key from an array of objects.

This article will delve into two different algorithms designed to achieve this goal, concluding with a suggestion on how to generalize the method for efficient reuse.

Starting Data Structure

Before diving in, let’s familiarize ourselves with the dataset we’ll be using. The critical elements here are the array name (data) and the key we are focusing on throughout this guide (Market).

const data = [{

"Name": "Adobe Systems Incorporated",

"Sector": "Technology",

"Market": "NASDAQ"

}, {

"Name": "American River Bankshares",

"Sector": "Finance",

"Market": "NASDAQ"

}, {

"Name": "iStar Financial Inc.",

"Sector": "n/a",

"Market": "NYSE"

}, {

"Name": "Prothena Corporation plc",

"Sector": "Health Care",

"Market": "NASDAQ"

}, {

"Name": "Matrix Service Company",

"Sector": "Basic Industries",

"Market": "NASDAQ"

}];

Chaining .map() and .filter()

The first approach expands on the second method discussed in the previous article by utilizing map() and filter(). The map() function transforms each element of the array, while filter() is employed to return a subset of those elements. By chaining these two methods, we can convert the array of objects into an array of strings and subsequently filter out any duplicates.

const uniques = data.map((obj) => obj.Market)

.filter((item, index, arr) => arr.indexOf(item) === index);

Mastering the use of .map() and .filter() is extremely beneficial. For further insights and examples, refer to our additional articles on these topics.

Discover how to get a unique list of objects in an array using JavaScript. This video will guide you through the process step-by-step.

Modifying with Spread/Set Technique

Our second method is more streamlined and typically easier to interpret. However, utilizing the spread operator (...) requires ES6, which may not be compatible with older JavaScript versions.

The fundamental strategy of this algorithm again uses map() to transform the array of objects into an array of strings. A Set is then created, which inherently disallows duplicate values. Finally, we’ll utilize the spread operator to create a new array from this set.

const uniques = [...new Set(data.map((obj) => obj.Market))];

Upgrading to a Functional Approach

A significant difference when working with an array of objects versus an array of strings is that the object key can vary. This makes it challenging to directly copy and reuse the code snippet since we have to specify the object key inline.

To enhance the reusability of our algorithm, let’s create a function that accepts two parameters (the array of objects and the key name) and returns an array of unique values.

function uniqueKeyValues(arr, key) {

return [...new Set(arr.map((obj) => obj[key]))];

}

Keep in mind that we can also apply the map() and filter() technique within this function. Simply replace data with arr and substitute .Market with [key], similar to what we did with the spread/set technique.

Explore three simple methods to extract unique values from an array in JavaScript. This video offers practical tips and techniques for developers.

In closing, please share your thoughts, questions, and feedback below. Follow Code 85 for more straightforward programming guides. Thank you for reading!

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

# Technology Sector: The Driving Force of the Modern Economy

Exploring the tech sector's role in the economy, investment opportunities, and challenges within a rapidly evolving landscape.

Exploring Mushroom Coffee: Trend or Treasure?

Dive into the world of mushroom coffee—its benefits, taste, and whether it's worth the hype.

Harnessing the Universal Law of Attraction for Personal Growth

Discover how the Universal Law of Attraction can transform your life through focused thoughts and intentional actions.