一. 数组元素仅包含数字
1、使用数组indexOf
var removeDuplicates = function(nums) {
for (let i = 0; i < nums.length;) {
if (nums.indexOf(nums[i]) !== i) {
nums.splice(i, 1);
} else {
i++;
};
};
return nums;
};
let list =[1,1,2]
console.log(removeDuplicates(list));
2、使用ES6 set
let arr = [1,0,0,2,9,8,3,1];
function unique(arr) {
return Array.from(new Set(arr))
}
console.log(unique(arr)); // [1,0,2,9,8,3]
二. 数组元素为对象
function uniqueList(arr1, arr2, key) {
let arr = arr1.concat(arr2);
let hash = {};
return arr.reduce((item, next) => {
hash[next[key]] ?
"" :
(hash[next[key]] = true && item.push(next));
return item;
}, []);
}
let arr1=[
{k:'1'},
{k:'2'},
{k:'3'},
]
let arr2=[
{k:'1'},
{k:'3'},
{k:'4'},
]
console.log(uniqueList(arr1,arr2,'k'));//[{"k":"1"},{"k":"2"},{"k":"3"},{"k":"4"}]