/* 根据数组中的字段去重 */
var arr = [
{"id":"1001","name":"值1","value":"123"},
{"id":"1001","name":"值1","value":"456"},
{"id":"1002","name":"值2","value":"789"},
{"id":"1002","name":"值2","value":"753"},
{"id":"1002","name":"值2","value":"951"},
{"id":"1003","name":"值3","value":"852"},
{"id":"1003","name":"值3","value":"654"}
];
function arrayUnique(arr, id) {
var hash = {};
return arr.reduce(function (item, next) {
hash[next[id]] ? '' : hash[next[id]] = true && item.push(next);
return item;
}, []);
}
console.log(arrayUnique(arr,'id'))
/* 数组去重方法一 */
var removeDuplicates = function(nums) {
nums = nums.sort();
function loop(nums){
for(var i=1;i<=nums.length;i++){
if(nums[i] === nums[i-1]){
nums.splice(i,1);
loop(nums);
return;
}
}
}
loop(nums);
return nums;
};
console.log(removeDuplicates([1,1,2,2,3]));
console.log(removeDuplicates([0,0,1,1,1,2,2,3,3,4]));
/* 数组去重方法二 */
var removeDuplicates1 = function(nums) {
var set = new Set();
for(var i =0;i<nums.length;i++){
set.add(nums[i]);
}
return [...set];
}
console.log(removeDuplicates1([1,1,2,2,3]));
console.log(removeDuplicates1([0,0,1,1,1,2,2,3,3,4]));
/* 数组去重方法三 */
[0,0,1,1,1,2,2,3,3,4].reduce((curr, next) => curr.indexOf(next) === -1 ? curr.concat(next) : curr, []);
/*数组去重方法四*/
[...new Set([1,2,2,3,3])]