js數組去重,老生長談,今天對其進行一番概括,總結出來4種方法數組
貼入代碼前 ,先對瀏覽器Array對象進行支持indexOf和forEach的polyfill瀏覽器
Array.prototype.indexOf = Array.prototype.indexOf || function(item) { for (var i = 0, j = this.length; i < j; i++) { if (this[i] === item) { return i; } } return -1; } Array.prototype.forEach = Array.prototype.forEach || function(callback, thisArg) { if (!callback || typeof callback !== 'function') return; for (var i = 0, j = this.length; i < j; i++) { callback.call(thisArg, this[i], i, this); } }
方法一:遍歷數組,創建新數組,利用indexOf判斷是否存在於新數組中,不存在則push到新數組,最後返回新數組this
1 function removeDuplicatedItem(ar) { 2 var ret = []; 3 4 for (var i = 0, j = ar.length; i < j; i++) { 5 if (ret.indexOf(ar[i]) === -1) { 6 ret.push(ar[i]); 7 } 8 } 9 10 return ret; 11 }
方法二:遍歷數組,利用object對象保存數組值,判斷數組值是否已經保存在object中,未保存則push到新數組並用object[arrayItem]=1的方式記錄保存spa
function removeDuplicatedItem2(ar) { var tmp = {}, ret = []; for (var i = 0, j = ar.length; i < j; i++) { if (!tmp[ar[i]]) { tmp[ar[i]] = 1; ret.push(ar[i]); } } return ret; }
方法三:數組下標判斷法, 遍歷數組,利用indexOf判斷元素的值是否與當前索引相等,如相等則加入prototype
function removeDuplicatedItem3(ar) { var ret = []; ar.forEach(function(e, i, ar) { if (ar.indexOf(e) === i) { ret.push(e); } }); return ret; }
方法四:數組先排序, 而後比較倆數組一頭一尾進行去重code
function removeDuplicatedItem4(ar) { var ret = [], end; ar.sort(); end = ar[0]; ret.push(ar[0]); for (var i = 1; i < ar.length; i++) { if (ar[i] != end) { ret.push(ar[i]); end = ar[i]; } } return ret; }
有其餘好的方式 ,歡迎補充。對象