Javascript needs to use Set in some cases. The following article will take you to understand Set, introduce what Set is, when to use Set, and the data operations of Set (intersection, difference set, intersection, symmetric difference set).

In many cases, you need to compare multiple lists to obtain whether they have intersection or difference, etc. There is a data type in Javascript that can achieve this very well. Demand, that is Set.
SetThe object is like an array, but contains only unique items. SetThe object is a collection of values, and its elements can be iterated in the order of insertion. The elements in Set will only appear once, that is, the elements in Set are unique.
The code address involved in the article: https://codepen.io/quintiontang/pen/rNmNbbY
What is Set
Set The object is a collection of values. Its elements can be iterated in the order of insertion. The elements will only appear once, that is, Set is not in a specific order. A stored collection of unique values. Unlike other collection types such as stacks, queues, and arrays, Sets can be used for list comparisons and for detecting the presence of an item in a set.
Set is an abstract data type that is defined by its behavior, similar to stack and queue data structures. Due to the characteristics of key-key, this is similar to Map.
Javascript Set
Set in Javascript is very basic and simple, it doesn’t provide as much as other languages General set operation functions. It uses a unique algorithm (not based on strict equality ===) to detect whether elements are identical.
This means that storing undefined, null and NaN in the collection will only be stored once, even if it is NaN != = NaN, which is usually applied to the storage of object types.
const setTest = new Set([0, -0, Infinity,null, undefined, null, NaN, NaN, Infinity,null]);
console.log(setTest); // Set { 0, Infinity, null, undefined, NaN }The following conclusions can be drawn from the above execution results:
- Although
NaNandNaNare not equal, but inSetThere will only be one -
undefinedin the set andInfinityThere will only be one# in theSet set
mozilla website.
When to use Set
When you need to compare a specific list and determine whether it is equal, you can use Set , let’s describe the applicable occasions, mainly the set operations in the data:
- Get the union of two sets
- union
- difference
- intersection
- intersectionDifference
- isSubset
- isSuperset
Set based on these three occasions.
Set Operations
In mathematics, whenever we talk about sets, there are some operations that can be performed, in fact, Set is the computer implementation of mathematical finite sets.
Set operation in the code, the sample code will extend Javascript Set to inherit its properties and methods, and add other methods to it.
For the sample code, only a simple method is used to check whether it is a valid collection that is not empty.
class SetHelper extends Set {
/**
* 验证集合是否为有效集合
* @param {*} set
* @returns
*/
_isValid = (set) => {
return set && set instanceof Set && set.size > 0;
};
}
Unionunion
The operation will merge multiple Set Object and return the combined result. The implementation merges the current set and the given set into an array and creates it, thus returning a new set. <pre class="brush:php;toolbar:false">union(set) {
if (!this._isValid(set)) return new SetHelper();
return new SetHelper([...this, ...set]);
}</pre>
difference
The operation will return a new set that is only contained in one set Elements that are in and not in another set, that is, the mathematical concept of difference set. <pre class="brush:php;toolbar:false">difference(set) {
if (!this._isValid(set)) return new SetHelper();
const differenceSet = new SetHelper();
this.forEach((item) => {
!set.has(item) && differenceSet.add(item);
});
return differenceSet;
}</pre>
intersection
The operation returns a new collection containing only elements common to both collections. The implementation will iterate over the smaller collection (avoiding unnecessary checks) and check if each item exists in the larger collection and add it to the intersection, which will be returned after the traversal is complete. <pre class='brush:php;toolbar:false;'>intersection(set) {
const intersectionSet = new SetHelper();
if (!this._isValid(set)) return intersectionSet;
const [smallerSet, biggerSet] =
set.size <= this.size ? [set, this] : [this, set];
smallerSet.forEach((item) => {
biggerSet.has(item) && intersectionSet.add(item);
});
return intersectionSet;
}</pre>
intersectionDifference##intersectionDifference
intersectionDifference(set) {
if (!this._isValid(set)) return new SetHelper();
return new SetHelper([
...this.difference(set),
...set.difference(this),
]);
}subset subset<p><code>isSubset 操作将判断两个集合是否为子集关系(当一个集合的所有项都包含在另一个集合中时)。实现上首先检查两个集合的大小,如果一个集合更大,则它不能是另一个集合的子集,然后对于每个项目,它检查它是否存在于另一个中。
isSubset(set) {
if (!this._isValidSet(set)) return false;
return (
this.size <= set.size && [...this].every((item) => set.has(item))
);
}超集 superset
isSuperset 操作将判断两个集合是否为超集关系。超集是子集的反操作。当一个集合包含另一个较小或相等大小的集合的所有项目时,它就是一个超集。
isSuperset(set) {
if (!this._isValidSet(set)) return false;
return (
this.size >= set.size && [...set].every((item) => this.has(item))
);
}静态 Set
静态Set 是一个始终包含它初始化元素的集合,不能添加、删除、清除元素。Javascript Set 不是静态的,它总能在创建后可以公开修改该集合的方法,如 add、delete ,为避免集合被修改,可以创建一个新的 Set ,将其修改方法重置 。
class StaticSet extends SetHelper {
constructor(items) {
super(items);
this.add = undefined;
this.delete = undefined;
this.clear = undefined;
}
}使用
现在就可以使用上面定义的方法操作两个 Set,如下:
const setA = new StaticSet(new Set([1, 2, 3, 4])); const setB = new StaticSet(new Set([3, 4, 5, 6])); console.log([...setA.union(setB)]); // [ 1, 2, 3, 4, 5, 6 ] console.log([...setA.difference(setB)]); // [ 1, 2 ] console.log([...setA.intersection(setB)]); // [ 3, 4 ] console.log([...setB.intersectionDifference(setA)]); // [ 5, 6, 1, 2 ]
总结
Set 不限于上面这些操作,之前有介绍过可以用来合并数组去重,由于 Set 和 Array 相互转换很简单,因此可以用到 Array 的场合可以优先考虑一下 Set ,因为在内存使用上, Set 比 Array 占用更少。
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of What is Set in JavaScript? When to use? how to use?. For more information, please follow other related articles on the PHP Chinese website!
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools







