set2. has(x)))", the intersection elements will be included in a set collection and returned; 3. Convert the set collection containing the intersection elements to an array type, using the syntax "Array.from(rse)"; 4. Determine whether the intersection array Is an empty array, if so there are no identical items, otherwise there are identical items."/> set2. has(x)))", the intersection elements will be included in a set collection and returned; 3. Convert the set collection containing the intersection elements to an array type, using the syntax "Array.from(rse)"; 4. Determine whether the intersection array Is an empty array, if so there are no identical items, otherwise there are identical items.">
search
HomeWeb Front-endFront-end Q&AHow to detect whether two arrays have the same items in es6

Detection steps: 1. Convert both arrays to set type, syntax "new Set(arr)"; 2. Get the intersection of two sets, syntax "new Set([...set1].filter (x=>set2.has(x)))", the intersection elements will be included in a set collection and returned; 3. Convert the set collection containing the intersection elements to an array type, the syntax is "Array.from(rse)" ;4. Determine whether the intersection array is an empty array. If so, there are no identical items. Otherwise, there are identical items.

How to detect whether two arrays have the same items in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Detecting whether two arrays have the same items is to detect whether the two arrays intersect.

Detection idea:

  • Get the intersection of two arrays

  • Determine whether the intersection is empty. If it is empty, there are no identical items. If it is not empty, there are identical items.

Implementation steps:

1. Obtain the intersection of two arrays

In es6, you can use the has() method of the set object in conjunction with the filter() of the array to find the intersection of two arrays.

  • Set is a new data structure provided by ES6, which is similar to an array, but has no duplicate values. Using this feature, we can convert the array to a Set type for deduplication, and then use the Array.from method to convert it to an array again.

  • The Set has() method indicates whether the Set object contains the specified value. Returns true if the specified value exists, false otherwise.

Note: If you want to use the has() method, you need to convert the array to a set collection type first

let a=[1, 2, 3];
let b=[3, 5, 2];
newA = new Set(a);
newB = new Set(b); 
let intersectionSet = new Set([...newA].filter(x => newB.has(x)));
console.log(intersectionSet);

How to detect whether two arrays have the same items in es6

As you can see At this time, the intersection elements are included in a set collection and return

2. Convert the set collection containing the intersection elements into an array type

In es6, you can use The Array.from method converts a collection into an array type

  • The Array.from method is used to convert two types of objects into real arrays: array-like objects and array-like objects. Iterable (iterable) objects (including ES6's new data structures Set and Map).

let intersectionSet = Array.from(new Set([...newA].filter(x => newB.has(x))));
console.log(intersectionSet);

How to detect whether two arrays have the same items in es6

3. Determine whether the intersection array is an empty array

  • If If it is an empty array, there will be no identical items

  • If it is not an empty array, there will be identical items

if(intersectionSet==[]){
	console.log("没有相同项");
}else{
	console.log("有相同项");
}

Complete code example:

let a=[1, 2, 3];
let b=[3, 5, 2];
console.log(a);
console.log(b);
newA = new Set(a);
newB = new Set(b); 
let intersectionSet = Array.from(new Set([...newA].filter(x => newB.has(x))));
console.log("两个数组的交集:");
console.log(intersectionSet);
if(intersectionSet==[]){
	console.log("没有相同项");
}else{
	console.log("有相同项");
}

How to detect whether two arrays have the same items in es6

[Related recommendations: javascript video tutorial, programming video

The above is the detailed content of How to detect whether two arrays have the same items 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
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.