数组去重
最简洁的做法
function unique(arr){
return [...new Set(arr)];
}
对象属性的唯一性
function unique(arr){
let res = [];
let obj = new Object();
arr.forEach(e => {
if(!obj[e]){
obj[e] = 1;
res.push(e);
}
});
return res;
}
一般的做法
function unique(arr){
let seen = [];
arr.forEach(e => {
if(seen.indexOf(e) < 0){
seen.push(e);
}
});
return seen;
}
console.log(unique([1,1,1,1,3,4]));
python实现-普通做法
def unique(arr):
seen = []
for i in arr:
if i not in seen:
seen.append(i)
return seen
c++实现-普通做法
# include<iostream>
# include<cstring>
# include<cstdlib>
using namespace std;
int* unique(int arr[]){
int seen[] = ;
}
int main(){
int arr[] = {1,1,1,1,1,3,4};
const int n = sizeof(arr) / sizeof(*arr);
unique(arr);
for(int i=0;i<n;i++){
cout<<arr[i]<<endl;
}
return 0;
}