惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The GitHub Blog
The GitHub Blog
L
Lohrmann on Cybersecurity
T
Threatpost
T
Threat Research - Cisco Blogs
C
Cybersecurity and Infrastructure Security Agency CISA
S
Schneier on Security
Engineering at Meta
Engineering at Meta
Scott Helme
Scott Helme
博客园 - 三生石上(FineUI控件)
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Visual Studio Blog
I
Intezer
L
LangChain Blog
Apple Machine Learning Research
Apple Machine Learning Research
S
Securelist
C
Cyber Attacks, Cyber Crime and Cyber Security
B
Blog RSS Feed
M
MIT News - Artificial intelligence
V
Vulnerabilities – Threatpost
T
The Exploit Database - CXSecurity.com
NISL@THU
NISL@THU
Cisco Talos Blog
Cisco Talos Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Know Your Adversary
Know Your Adversary
H
Hackread – Cybersecurity News, Data Breaches, AI and More
阮一峰的网络日志
阮一峰的网络日志
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The Cloudflare Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Vercel News
Vercel News
Stack Overflow Blog
Stack Overflow Blog
The Hacker News
The Hacker News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Register - Security
The Register - Security
Simon Willison's Weblog
Simon Willison's Weblog
Security Latest
Security Latest
C
Cisco Blogs
量子位
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed
Cyberwarzone
Cyberwarzone
Y
Y Combinator Blog
C
CERT Recently Published Vulnerability Notes
T
Tenable Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
AWS News Blog
AWS News Blog
Project Zero
Project Zero
D
Darknet – Hacking Tools, Hacker News & Cyber Security
A
Arctic Wolf
K
Kaspersky official blog

Josh Collinsworth

LLMs and performative productivity Man Cereal My review of the Nüborn Baby at 3 months 2025 Year in Review AI optimism is a class privilege Alchemy Titles matter The blissful zen of a good side project Goodbye, Griff. You were a good boy. Rare words in common phrases, and how to avoid getting them wrong Things I enjoyed in 2024 The childlike and the childish A response to "Defending Open Source: Protecting the Future of WordPress" If WordPress is to survive, Matt Mullenweg must be removed For whatever it's worth: my advice on job hunting in tech A decade of code Follow-up: the Glove80 after six months The quiet, pervasive devaluation of frontend I worry our Copilot is leaving some passengers behind Things I enjoyed in 2023 First impressions of the MoErgo Glove80 ergonomic keyboard A message from the Captain of the S.S. Layoff Things you forgot (or never knew) because of React Alfred vs. Raycast: my constant debate Adding page transitions in SvelteKit Ten tips for better CSS transitions and animations Understanding easing and cubic-bezier curves in CSS Impressions of the ZSA Moonlander at one month Why you should never use px to set font-size in CSS Forty-two Breaking changes in SvelteKit, August 2022 The self-fulfilling prophecy of React Announcing Hondo Building accessible toggle buttons (with examples for Svelte, Vue, and React) Debugging iOS Safari (when all you have is a Mac) Creating dynamic bar charts with CSS grid Let's learn SvelteKit by building a static Markdown blog from scratch Adding blog comments to your static site with utterances Converting from Gridsome to SvelteKit Introducing Svelte, and Comparing Svelte with React and Vue Goodbye, WordPress Announcing Quina (My First App)! How to Create Custom Editor Blocks with Block Lab A New Headless Site with Gridsome This isn't the Time, But it's the Perfect Time; Goodbye, Instagram How to Connect Local with CodeKit Adding Gutenberg Full- and Wide-Width Image Support to Your WordPress Theme Let's Learn CSS Variables! New Site, New Theme for 2018 Five Ways to Become a Better Designer (That Aren't Design) My Essential Tools for WordPress Development The Five Things I Wish Somebody Had Told Me as a Design Student WordPress Child Theme Explanation and Walkthrough Why Designers Shouldn't "Fix" Other Designers' Logos 8 Mistakes to Avoid in Your Student Design Portfolio Profit is Not a Value Understanding the Difference Between Image and Vector File Types Pantone, Color, and What I Wish I Had Known Sooner as a Designer Social Media, Compulsion, and the 12 Things I Learned on My Break from Facebook Classic rock, Mario Kart, and why we can't agree on Tailwind
How to Check Uniqueness in an Array of Objects in JavaScript
2020-02-17 · via Josh Collinsworth

Published: February 17, 2020
Last updated: May 19, 2020

Recently, working on my Svelte side project (smitty.netlify.com), I came across the need to verify that all object properties in an array of objects were unique.

That’s a little tough to explain in writing, so here’s an example:

const items = [
	{
		name: 'The first object',
		id: 1
	},
	{
		name: 'Another object',
		id: 42
	},
	{
		name: 'Here is a third object',
		id: 100
	},
	{
		name: 'Oops! This one is a duplicate',
		id: 42
	}
	// ...etc.
];

In my case, the IDs were hard-coded (rather than generated programmatically). As such, they were subject to human error, and I discovered that some IDs were duplicated.

This was an issue because the ID numbers were being used for setting the HTML ids in a form; that meant some of the <label> elements were being associated with the wrong input, which is pretty disastrous in a production app!

The solution:

How to find the duplicates though? In my case there were 100 unique objects in the array, so while combing through them manually certainly wasn’t impossible, it was going to be a tedious task. The solution was to use JavaScript’s map method and Set functionality.

  • map takes an array, and maps each thing in that array to a new array. (Here, we use it to create a new array with just the original IDs.)
  • Sets in JavaScript create new arrays (technically, sets) with only unique values. (For example, the Set of [0, 0, 1, 1, 2] is [0, 1, 2]

To extract only the IDs of the original array, the code looks like this (where the original array is named items):

const IDs = new Set(items.map((item) => item.id));

Now we’ve got an array of only unique IDs. What next?

Well, if we did have duplicate IDs in our original items array, then the length of IDs will be different than the length of the original array. So it’s a quick conditional check, which would seem like this, but beware! We’re missing a step:

IDs.length === items.length;
// Always returns false 🤔

Heads up! That won’t quite work, because Sets and arrays in JavaScript are not the same thing! The above comparison will always return false because, if you check, IDs.length is undefined. (That’s because .length is a method on arrays, not sets.)

To fix the issue, we can just add a bit of ES6 destructuring to convert the set into an array:

[...IDs].length === items.length;
// Now it works!
// true if all IDs were unique, false if not

If you prefer, this is a little more explicit and works the same way; I just prefer the above shorthand, personally:

// Another way to do the same thing:
Array.from(IDs).length === items.length;

Make it reusable

If this is an issue you might run into frequently, you can abstract it to a function like so:

// Reusable function to check uniqueness of keys in an array of objects
const isEverythingUnique = (arr, key) => {
    const uniques = new Set(arr.map(item => item[key]);
    return [...uniques].length === arr.length;
}

And call it with, e.g., isEverythingUnique(items, 'id'); (which would return false in our case, because there are two objects each with id: 42).

If the function returns true, then you know all the keys are unique. Otherwise, you have non-unique keys (IDs).

To find out which ones are duplicates, you can use this handy function which I developed from this Hacker Noon post:

// Reusable function to show the duplicate keys in an array of objects
const getDuplicates = (arr, key) => {
	const keys = arr.map((item) => item[key]);
	return keys.filter((key) => keys.indexOf(key) !== keys.lastIndexOf(key));
};

Call this function just like the one above, e.g., getDuplicates(items, 'id'), which in our case, would get you an array that contains the non-unique IDs, like this:

getDuplicates(items, 'id');

// [42, 42]

Hope you enjoyed! Thanks for reading.