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

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

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

*/
文章作者: Lete乐特
文章链接: https://blog.lete114.top/article/JavaScript-array-unique.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Lete乐特's Blog
  • alipay
  • wechat

评论