ES6数组去重的常用方法
数组去重的常用方法汇总:
方法一:
1 | [...newSet(test)]; |
方法二:
1 | Array.from() |
1 2 | const test = [ 'q' , 'w' , 'e' , 'q' , 'u' , 'p' ] Array.from( new Set(test)) |
方法三:
1 2 3 4 | function unique(arr) { const res = new Map(); return arr.filter((a) => !res.has(a) && res.set(a, 1)) } |
方法四:
数组中对象去重;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | let test = [ { imageId: '1' , imageUrl: 'https://raw.githubusercontent.com/perfectSymphony/vue-admin/master/src/assets/logo.png' , }, { imageId: '1' , imageUrl: 'https://raw.githubusercontent.com/perfectSymphony/vue-admin/master/src/assets/logo.png' , }, { imageId: '2' , imageUrl: 'https://raw.githubusercontent.com/perfectSymphony/vue-admin/master/src/assets/logo.png' , }, { imageId: '3' , imageUrl: 'https://raw.githubusercontent.com/perfectSymphony/vue-admin/master/src/assets/logo.png' , }, { imageId: '3' , imageUrl: 'https://raw.githubusercontent.com/perfectSymphony/vue-admin/master/src/assets/logo.png' , }, { imageId: '4' , imageUrl: 'https://raw.githubusercontent.com/perfectSymphony/vue-admin/master/src/assets/logo.png' , } ]<br><br> objTrim: function (){ let obj = {}; this .test= this .test.reduce((cur,next) => { obj[next.imageId] ? "" : obj[next.imageId] = true && cur.push(next); return cur; },[]); return this .test; }, |
------------------------------------------------------------------------------------------------------------------------------------------------
ES5:
方法一: (更新于2020年4月15日):
思路:
- 1. 创建一个新的空数组,用来存放去重后的新数组.
- 2. 利用for循环循环遍历需要去重的数组.
- 3. 利用
indexOf()
方法查询遍历出的数组在新数组中是否出现,如果出现:则继续遍历数组,如未出现:则利用push方法添加到新数组中. - 4. 原数组循环遍历完成后,组建一个已经去除重复的新数组.
var arr = [1,3,4,5,6,7,4,3,2,4,5,6,7,3,2]; function find(){ var newArr = []; for (var i = 0; i < arr.length; i++) { if (newArr.indexOf(arr[i]) == -1 ) { newArr.push(arr[i]); } } document.write(newArr); } find(arr);
欢迎issue!!!
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步