JavaScript去除数组重复字段

数据如下,现在数据冗余了(太多重复且无用的数据)

COPY
1
2
3
4
5
6
var type = ["菜鸟","大佬","小白","小白","小白","菜鸟","大佬","大佬","大佬","大佬","大佬","大佬","大佬"]

// 怎么才能得到 [菜鸟,大佬,小白] 三个字段呢?
// 结果应该是要这样
var type = ["菜鸟","大佬","小白"]

完整代码

COPY
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var type = ["菜鸟","大佬","小白","小白","小白","菜鸟","大佬","大佬","大佬","大佬","大佬","大佬","大佬"]

// 将相同的值相邻,然后遍历去除重复值
function unique(array) {
array.sort();
var result = [array[0]];
for (var i = 1; i < array.length; i++) {
if (array[i] !== result[result.length - 1]) {
result.push(array[i]);
}
}
return result;
}
console.log(unique(type));
/*

控制台结果:[ '大佬', '小白', '菜鸟' ]

*/
Authorship: Lete乐特
Article Link: https://blog.imlete.cn/article/JavaScript-array-unique.html
Copyright: All posts on this blog are licensed under the CC BY-NC-SA 4.0 license unless otherwise stated. Please cite Lete乐特 's Blog !