Set trong JS là một tập hợp nhiều phần tử, set chỉ có thể chứa các phần tử khác nhau (mỗi phần tử là độc nhất).

Construction

Tạo set rỗng:

const companies = new Set()
 
console.log(companies) // => Set(0)

Cách khởi tạo tương tự như khởi tạo một object với default constructor (xem thêm JS Objects).

Tạo set từ array:

const languages = [
	"English",
	"Finnish",
	"English",
	"French",
	"Spanish",
	"English",
	"French",
]
 
const setOfLanguages = new Set(languages)
 
console.log(setOfLanguages) // Set(4) {English, Finnish, French, Spanish}

Ta có thể duyệt qua từng phần tử trong set như mảng thông thường:

for (const language of setOfLanguages) {
	console.log(language)
} // English, Finnish, French, Spanish

Instance Methods

Add

Dùng phương thức add để thêm một phần tử vào set:

const companies = ["Google", "Facebook", "Amazon", "Oracle", "Microsoft"]
const setOfCompanies = new Set()
 
for (const company of companies) {
	setOfCompanies.add(company)
}
 
console.log(setOfCompanies) // Set(5) {"Google", "Facebook", "Amazon", "Oracle", "Microsoft"}

Delete

Dùng phương thức delete để xóa một phần tử:

console.log(setOfCompanies.delete("Google"))
console.log(setOfCompanies.size) // 4

Has

Dùng phương thức has để kiểm tra một phần tử có trong set hay không:

console.log(setOfCompanies.has("Apple")) // false
console.log(setOfCompanies.has("Facebook")) // true

Clear

Dùng phương thức clear để xóa hết mọi phần tử có trong set:

setOfCompanies.clear()

Applications

Ứng dụng của set là để lọc ra mảng các phần tử khác nhau từ mảng ban đầu. Do đó, có thể dùng để đếm số phần tử unique trong mảng:

const numbers = [5, 3, 2, 5, 5, 9, 4, 5]
const setOfNumbers = new Set(numbers)
 
console.log(setOfNumbers) // Set(5) {5, 3, 2, 9, 4}

Union of Sets

Để tìm hợp của hai tập hợp:

const a = [1, 2, 3, 4, 5]
const b = [3, 4, 5, 6]
const c = [...a, ...b] // merge
 
const A = new Set(a)
const B = new Set(b)
let union = new Set(c) // filter unique element
 
console.log(union) // [1, 2, 3, 4, 5, 6]

Intersection of Sets

Có thể dùng phương thức has để tìm giao của hai set. Tức là lọc ra các phần tử của a có tồn tại trong b.

const intersection = a.filter(function (num) {
	return B.has(num)
})
 
console.log(intersection) // [3, 4, 5]

Difference of Sets

Tìm phần bù của A và B (A / B), ta sử dụng phương thức has để loại bỏ những phần tử thuộc cả A và B.

const complement = a.filter(function (num) {
	// If exists in B => filter out
	return !B.has(num)
}) 
 
console.log(complement) // [1, 2]
table tags as Tags, file.cday as Created
from [[JS Set]]
sort file.ctime asc