搜索
首页web前端前端问答es6怎么实现arr(数组)去重

es6怎么实现arr(数组)去重

Aug 30, 2022 pm 05:48 PM
javascriptes6es6数组

3种实现方法:1、Set数据结构和“Array.from()”去重,语法“Array.from(new Set(arr))”;2、Set数据结构和扩展运算符“...”去重,语法“[...new Set(arr)]”;3、filter()和indexOf()过滤,语法“arr.filter((it,in)=>{return arr.indexOf(it,0)===in;});”。

es6怎么实现arr(数组)去重

本教程操作环境:windows7系统、ECMAScript 6版、Dell G3电脑。

ES6数组去重的5种方法

1、Set数据结构和Array.from()去重

  • Set是ES6新提供的数据结构,类似于数组,但是本身没有重复值。利用这一特性,我们可以将数组转为Set类型进行去重,然后使用Array.from方法将其再转为数组。

  • Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。

实现思想:

  • 将数组转为set集合去重后,使用Array.from方法将集合转为数组

语法:

Array.from(new Set(arr))

示例:

let arr=[1,2,3,3,2,"1",0,undefined,undefined];
let newArr=Array.from(new Set(arr));
console.log(newArr);

1.png

2、Set数据结构和扩展运算符“...”去重

  • 扩展运算符是ES6中引入的,将可迭代对象展开到其单独的元素中,所谓的可迭代对象就是任何能用for of循环进行遍历的对象,例如:数组、字符串、Map 、Set 、DOM节点等。

实现思想:

  • 将数组转为set集合去重后,使用扩展运算符…将集合展开到数组中,将集合转为数组

语法:

[...new Set(arr)]

示例:

let arr=[1,2,3,3,2,"1",0,1,2];
let newArr=[...new Set(arr)];
console.log(newArr);

2.png

3、利用数组的 filter+indexOf方法去重

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

indexOf方法返回指定元素在数组中的第一个索引(index), 如果没有则返回 -1

示例:

var arr=[1, 2, 3, 2, 3];
var newArr = arr.filter((item,index)=> {
  return arr.indexOf(item,0) === index;
});
console.log(newArr);

3.png

所以这里的 arr 数组中的每个元素通过 indexOf() 方法返回的索引值分别是 0 1 2 1 2

arr.forEach(item => console.log(arr.indexOf(item))); // 0 1 2 1 2

可以通过 indexOf 来实现去重,比如 arr 中的第四个元素 2 通过 indexOf 返回的是索引是 1, 但是它当前的 index 下标是 3,不相等,说明当前的这个 2 元素在之前出现过, 所以应该把它过滤掉。

【相关推荐:javascript视频教程web前端

以上是es6怎么实现arr(数组)去重的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
反应的局限性是什么?反应的局限性是什么?May 02, 2025 am 12:26 AM

Include:1)AsteeplearningCurvedUetoItsVasteCosystem,2)SeochallengesWithClient-SiderEndering,3)潜在的PersperformanceissuesInsuesInlArgeApplications,4)ComplexStateStateManagementAsappsgrow和5)TheneedtokeEedtokeEedtokeEppwithitsrapideDrapidevoltolution.thereedtokeEppectortorservolution.thereedthersrapidevolution.ththesefactorsshesssheou

React的学习曲线:新开发人员的挑战React的学习曲线:新开发人员的挑战May 02, 2025 am 12:24 AM

reactischallengingforbeginnersduetoitssteplearningcurveandparadigmshifttocoment oparchitecent.1)startwithofficialdocumentationforasolidFoundation.2)了解jsxandhowtoembedjavascriptwithinit.3)

为React中的动态列表生成稳定且独特的键为React中的动态列表生成稳定且独特的键May 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript疲劳:与React及其工具保持最新JavaScript疲劳:与React及其工具保持最新May 02, 2025 am 12:19 AM

javascriptfatigueinrectismanagbaiblewithstrategiesLike just just in-timelearninganning and CuratedInformationsources.1)学习whatyouneedwhenyouneedit

使用USESTATE()挂钩的测试组件使用USESTATE()挂钩的测试组件May 02, 2025 am 12:13 AM

totlecteactComponents通过theusestatehook,使用jestandReaCtteTingLibraryToSigulation Interactions andverifyStatAtaTeChangesInTheUI.1)renderthecomponentAndComponentAndComponentAndCheckInitialState.2)模拟useclicklicksorformsormissionsions.3)

React中的钥匙:深入研究性能优化技术React中的钥匙:深入研究性能优化技术May 01, 2025 am 12:25 AM

KeysinreactarecrucialforopTimizingPerformanceByingIneFefitedListupDates.1)useKeyStoIndentifyAndTrackListelements.2)避免使用ArrayIndi​​cesasKeystopreventperformansissues.3)ChooSestableIdentifierslikeIdentifierSlikeItem.idtomaintainAinainCommaintOnconMaintOmentStateAteanDimpperperFermerfermperfermerformperfermerformfermerformfermerformfermerment.ChosestopReventPerformissues.3)

反应中的键是什么?反应中的键是什么?May 01, 2025 am 12:25 AM

ReactKeySareUniqueIdentifiers usedwhenrenderingListstoimprovereConciliation效率。1)heelPreactrackChangesInListItems,2)使用StableanDuniqueIdentifiersLikeItifiersLikeItemidSisRecumended,3)避免使用ArrayIndi​​cesaskeyindicesaskeystopreventopReventOpReventSissUseSuseSuseWithReRefers和4)

反应中独特键的重要性:避免常见的陷阱反应中独特键的重要性:避免常见的陷阱May 01, 2025 am 12:19 AM

独特的keysarecrucialinreactforoptimizingRendering和MaintainingComponentStateTegrity.1)useanaturalAlaluniqueIdentifierFromyourDataiFabable.2)ifnonaturalalientedifierexistsistsists,generateauniqueKeyniqueKeyKeyLiquekeyperaliqeyAliqueLiqueAlighatiSaliqueLiberaryLlikikeuuId.3)deversearrayIndi​​ceSaskeyseSecialIndiceSeasseAsialIndiceAseAsialIndiceAsiall

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版