普通数组去重
Array.prototype.unique = function(){ var res = []; var json = {}; for(var i = 0; i < this.length; i++){ if(!json[this[i]]){ res.push(this[i]); json[this[i]] = 1; } } return res; } var arr = [112,112,34,'你好',112,112,34,'你好','str','str1']; alert(arr.unique());
json数组去重
arr=[{FromStation:'杭州',ToStation:'北京'},{FromStation:'杭州',ToStation:'北京'},{FromStation:'上海',ToStation:'北京'},{FromStation:'杭州',ToStation:'南京'}]
function unique(arr){ let newArr = [arr[0]]; for(let i = 1; i < arr.length; i++){ let Item = arr[i]; let repeat = false; for (let j = 0; j < newArr.length; j++) { if (Item.FromStation == newArr[j].FromStation && Item.ToStation == newArr[j].ToStation) { repeat = true; break; } } if (!repeat) { newArr.push(Item); } } return newArr; }
unique(arr) // arr=[{FromStation:'杭州',ToStation:'北京'},{FromStation:'上海',ToStation:'北京'},{FromStation:'杭州',ToStation:'南京'}]