数组去重的常用方法汇总:
方法一:
[...newSet(test)];
方法二:
Array.from()
const test = ['q', 'w', 'e', 'q', 'u', 'p'] Array.from(new Set(test))
方法三:
function unique(arr) { const res = new Map(); return arr.filter((a) => !res.has(a) && res.set(a, 1)) }
方法四:
数组中对象去重;
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', } ]
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!!!