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

推荐订阅源

P
Proofpoint News Feed
L
LangChain Blog
U
Unit 42
Apple Machine Learning Research
Apple Machine Learning Research
The Cloudflare Blog
Martin Fowler
Martin Fowler
T
Tenable Blog
IT之家
IT之家
H
Help Net Security
阮一峰的网络日志
阮一峰的网络日志
Forbes - Security
Forbes - Security
N
Netflix TechBlog - Medium
The Hacker News
The Hacker News
J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Tailwind CSS Blog
美团技术团队
NISL@THU
NISL@THU
T
Threatpost
GbyAI
GbyAI
T
Threat Research - Cisco Blogs
I
InfoQ
Jina AI
Jina AI
Microsoft Azure Blog
Microsoft Azure Blog
人人都是产品经理
人人都是产品经理
C
Check Point Blog
V
Vulnerabilities – Threatpost
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Spread Privacy
Spread Privacy
S
Securelist
大猫的无限游戏
大猫的无限游戏
P
Privacy & Cybersecurity Law Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
爱范儿
爱范儿
小众软件
小众软件
C
Cybersecurity and Infrastructure Security Agency CISA
Cisco Talos Blog
Cisco Talos Blog
Engineering at Meta
Engineering at Meta
S
Security Affairs
S
Secure Thoughts
T
Troy Hunt's Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
aimingoo的专栏
aimingoo的专栏
博客园 - 司徒正美
PCI Perspectives
PCI Perspectives
C
Cisco Blogs
MongoDB | Blog
MongoDB | Blog
Vercel News
Vercel News
月光博客
月光博客
Recorded Future
Recorded Future

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.