js:多种方法实现数组去重
2024-09-28 09:34:17
面试的时候数组去重要多种方法实现,
只想到一种判断重复删除的方法,而且还没写对。后来大概看了一下网上的方法。
下午想到一个网上没见过的filter方法,于是整理了一下,基于以前看到的思想,然后用了一些网上不一样的对象方法。
var arr = [1, 4, 2, 1, 5, 4, 2, 5, 6, '2', 3, 1]
// arr作为原始数据,用变量a拷贝arr,对数组a进行去重
// 自身重复比较(删除/添加)
var a = [...arr]
for (var i = a.length - 1; i > 0; i--) {
if (a.indexOf(a[i]) != i) a.splice(i, 1)
}
console.log('1.自己重复判断\n', a); //新数组重复判断
var b = []
arr.forEach((e, i) => {
if (b.indexOf(e) == -1) b.push(e)
});
console.log('2.新数组重复判断\n', b); //es6 set
a = [...arr]
b = []
b = [...new Set(a)]
console.log('3.set\n', b); //new Set(a):Set { 1, 4, 2, 5, 6, '2', 3 } //fillter
b = []
b = arr.filter((e, i) => arr.indexOf(e) == i)
console.log('4.fillter\n', b); //对象属性
var c = {}
b = []
arr.forEach(e => {
if (!c[e]) {
c[e] = true
b.push(e)
}
})
console.log('5.对象属性\n', b);
//sort 相邻比较
a = [...arr]
a.sort() //重写排序规则解决字符问题
a.reduceRight((t, e, i) => {
if (e == a[i + 1]) a.splice(i + 1, 1)
})
console.log('6.sort 相邻比较\n', a);
输出结果:
对象属性和sort()无法区分类似 4和‘4’的元素。sort()可以另写方法区分。
最新文章
- 使用Java中File类批量创建文件和批量修改文件名
- 解决 mysql 启动报错--发现系统错误2,系统找不到指定的文件
- javascript优化--09模式(代码复用)02
- Android notifications通知栏的使用
- PowerDesigner中导出设计说明文档
- java入门学习(十一)逻辑运算符和位运算符
- 跟着老男孩一步步学习Shell高级编程实战
- android Vibrator 用法
- 位图像素的颜色 携程编程大赛hdu
- linux系统 initrd.img中init启动脚本分析
- 分布式系统之消息中间件rabbitmq
- An invalid character [32] was present in the Cookie value 错误
- happens-before 理解
- c/c++ 标准库 string
- Mayor's posters POJ - 2528(线段树 + 离散化)
- Zabbix 添加对交换机端口流量超出阈值的监控
- 第 7 章 多主机管理 - 047 - 管理 Machine
- nginx是什么,如何使用
- vue打印html
- JAVA框架 Mybaits