1.数组去重

var arr = ['1','2','3','13','4','2','0','7','6','3','2'];
Array.prototype.unique = function() {
var temArr = new Array();
for(var i in this) {
if(typeof this[i] !== 'function' && temArr.join(',').indexOf(this[i]) < 0) {
temArr.push(this[i]);
}
}
return temArr;
}
function unique1(arr) {
return Array.from(new Set(arr));
}
console.info(arr.unique());
console.info(unique1(arr));



>>>["1", "2", "3", "13", "4", "0", "7", "6"]
>>>["1", "2", "3", "13", "4", "0", "7", "6"]


2.对象数组去重
 
const arr = [{id: 1},{id: 2},{id: 3},{id: 2}];
const hash = {};
const arrResult = arr.reduce((preVal, curVal) => {
  hash[curVal.id] ? '' : hash[curVal.id] = true && preVal.push(curVal);
  return preVal;
}, []);
console.info(arrResult);
 
 
>>> [{id: 1},{id: 2},{id: 3}]
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程