博客
关于我
js数组去重的多种方法
阅读量:750 次
发布时间:2019-03-23

本文共 1210 字,大约阅读时间需要 4 分钟。

数组去重

const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}]; // => [1, '1', 17, true, false, 'true', 'a', {}, {}]

方法一:利用Set

const res1 = Array.from(new Set(arr));

方法二:两层for循环+splice

const unique1 = arr => {   let len = arr.length;   for (let i = 0; i < len; i++) {     for (let j = i + 1; j < len; j++) {       if (arr[i] === arr[j]) {         arr.splice(j, 1);         // 每删除一个树,j--保证j的值经过自加后不变。同时,len--,减少循环次数提升性能        len--;         j--;       }     }   }   return arr;}

方法三:利用indexOf

const unique2 = arr => {   const res = [];   for (let i = 0; i < arr.length; i++) {     if (res.indexOf(arr[i]) === -1) res.push(arr[i]);   }   return res;}

当然也可以用include、filter,思路大同小异。

方法四:利用include

const unique3 = arr => {   const res = [];   for (let i = 0; i < arr.length; i++) {     if (!res.includes(arr[i])) res.push(arr[i]);   }   return res;}

方法五:利用filter

const unique4 = arr => {   return arr.filter((item, index) => {     return arr.indexOf(item) === index;   }); }

方法六:利用Map

const unique5 = arr => {   const map = new Map();   const res = [];   for (let i = 0; i < arr.length; i++) {     if (!map.has(arr[i])) {       map.set(arr[i], true)       res.push(arr[i]);     }   }   return res;}

转载地址:http://yrlzk.baihongyu.com/

你可能感兴趣的文章
Leetcode第557题---翻转字符串中的单词
查看>>
Problem G. The Stones Game【取石子博弈 & 思维】
查看>>
Java多线程
查看>>
openssl服务器证书操作
查看>>
我用wxPython搭建GUI量化系统之最小架构的运行
查看>>
selenium+python之切换窗口
查看>>
重载和重写的区别:
查看>>
搭建Vue项目步骤
查看>>
账号转账演示事务
查看>>
SpringBoot找不到@EnableRety注解
查看>>
在Vue中使用样式——使用内联样式
查看>>
Find Familiar Service Features in Lightning Experience
查看>>
Explore Optimization
查看>>
map[]和map.at()取值之间的区别
查看>>
【SQLI-Lab】靶场搭建
查看>>
【Bootstrap5】精细学习记录
查看>>
Struts2-从值栈获取list集合数据(三种方式)
查看>>
设计模式(18)——中介者模式
查看>>
推荐几篇近期必看的视觉综述,含GAN、Transformer、人脸超分辨、遥感等
查看>>
【专题3:电子工程师 之 上位机】 之 【46.QT音频接口】
查看>>