Home  >  Article  >  Web Front-end  >  How to use Set data structure to operate arrays in ES6

How to use Set data structure to operate arrays in ES6

php中世界最好的语言
php中世界最好的语言Original
2017-12-30 16:47:561753browse

What I bring to you this time is how to use the Set data structure to operate array in ES6. Our Set data structure is newly added in es6. It is similar to an array, but The value of the member is unique and there are no duplicate values. This article will give you a good analysis.

Set itself is a data structure, used to generate the Set data section.

Instances of the Set data structure have 4 traversal methods:

keys(): Returns a key Name traverser
values(): Returns a key-value convenience facility
entries(): Returns a key-value pair convenience facility
forEach(): Uses the callback function Traverse each member

Since the Set data structure has no key name, only key value (or key name and key value are the same value), so the behavior of keys and values ​​methods Totally consistent.

Therefore, using Set can easily realize intersection, union, and difference set

let a=new Set([1,2,3]);
let b=new Set([4,3,2]);
//交集
let union= [...new Set([...a,...b])];
console.log(union);
//并集
let intersect= [...new Set([...a].filter(x=> b.has(x)))];
console.log(intersect);
//差集
let difference= [...new Set([...a].filter(x=> !b.has(x)))];
console.log(difference);

I believe that after reading the above introduction, you have mastered the method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Related reading:

How to use JS bubbling events

Implementation of PHP cache optimization using memcached and xcache Steps

#How to customize the console object during the use of JS

The above is the detailed content of How to use Set data structure to operate arrays in ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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