Sets

王林
Release: 2024-08-26 21:42:32
Original
220 people have browsed it

Sets

  • Before ES6, JS had only two inbuilt Data Structures namely arrays & objects. ES6 introduced two new DS: Sets, Map.
  • For storage & orderly retirieveal use arrays.
  • Use sets only if order doesn't matter, and you just need to check the presence of element inside the data structure.
  • Sets are not intended to replace arrays. Arrays are more important.

- Whenever values need to be stored in order along with duplicates, arrays have to be used.

## Usecase: To remove duplicate values of arrays. const order = ['pizza','burger','pasta','noodles','pizza','noodles','burger']; const items = new Set(order); items; // All duplicate values are removed const city = new Set("California").size; city; // 8
Copy after login

Sets:

  • Sets are also iterables like String.
  • Collection of unique values.
const city = new Set("California"); city; // Set(8) { 'C', 'a', 'l', 'i', 'f', 'o', 'r', 'n' }
Copy after login
## Difference between Set & Array: 1. Although looks similar to array, but it has no key-value pairs. Hence, set[0] is invalid. 2. Only a list of unique values, all duplicate removed. 3. Order of element is irrelevant ## Similarities between Arrays & Sets: 1. Set has size property, Array has length propery. 2. Set has 'has' method, Array has includes method. const order = ['pizza','burger','pasta','noodles','pizza','noodles','burger']; const items = new Set(order); items; // Set(4) { 'pizza', 'burger', 'pasta', 'noodles' } //Both array and sets are iterables. Hence easier to convert from sets to array. [...items];
Copy after login

Adv: Can never have duplicate, although can hold mixed data types.
Most common iterable is Array. Ex. Syntax: new Set(iterable)

List of methods & properties on Sets:

.size; // returns a numerical value .has('name'); // returns a boolean value .add('name'); // returns the set with added value .delete('name'); // returns a boolean value .clear(); // deletes all elements. returns Set(0) {}
Copy after login

The above is the detailed content of Sets. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!