數組去重的常用方法匯總:
方法一:
[...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!!!