手写实现去重unique方法

多种实现方式:双层循环、indexOf、排序后去重、filter、Object 键值对、

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function unique(array, isSorted) {
var res = [];
var seen = [];

for (var i = 0, len = array.length; i < len; i++) {
var value = array[i];
if (isSorted) {
if (!i || seen !== value) {
res.push(value)
}
seen = value;
}
else if (res.indexOf(value) === -1) {
res.push(value);
}
}
return res;
}