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

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

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

完整代码

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));
/*

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

*/