当前位置:网站首页>(JS)数组去除重复
(JS)数组去除重复
2022-06-29 09:57:00 【不愿透露姓名的余菜鸟】
- 使用new Set()
var arr = [1,2,3,4,5,5,4,3,2,11,3,22,11,11,22];
let c = new Set(arr);
new Set()方法可以将所有不重复的值添加到新的Set中,然后返回
- 使用fliter()方法
var arr = [1,2,3,4,5,5,4,3,2,11,3,22,11,11,22];
let x = arr.filter(function(val,index),array) {
return array.indexOf(val)=== index;
}
filter()方法可以将满足条件的数值返回。使用indexOf查找array中当前值的索引是否等于index,如果等于说明数组中还不存在val,则返回一次,如果存在,则不返回。
- 使用循环判断
var arr = [1,2,3,4,5,5,4,3,2,11,3,22,11,11,22];
let newArr = [];
for(let i = 0; i<arr.length; i++) {
if(newArr.indexOf(arr[i]) === -1) {
newArr.push(arr[i]);
}
}
新建一个空数组,然后使用indexOf判断,如果等于-1,则表示空数组中没有当前项,则push进入新数组。此方法只能判断简单类型数值,如果需要判断undefined和NaN,Null则需要添加额外的判断条件。
- 使用reduce()方法去除重复
var arr = [1, 2, 3, 4, 5, 5, 4, 3, 2, 11, 3, 22, 11, 11, 22];
let x = arr.reduce(function(accumulation, current) {
if (!accumulation.includes(current)) {
accumulation.push(current);
}
return accumulation;
}, []);
reduce()方法是ES6中新加入的数组方法,可以用于累加计算,也可以用于判断某些项
边栏推荐
猜你喜欢

这个mySQL安装的时候怎么搞去了?

Daily question brushing record (VII)

基于STM32+RFID设计的宿舍检修管理系统

Exemples de programmation stm32f1 et stm32cubeide - entraînement du capteur de portée ultrasonique

UserWarning: Usage of dash-separated ‘script-dir‘ will not be supported in future versions. note

arcgis创建postgre企业级数据库

悬赏平台并没有WEB端开发,在原生开发和混合开发中哪种合适?

免费送书啦!畅销书《 OpenCV图像处理入门与实践》一本全搞定

反CSRF爆破的三种姿势

AQS之Atomic详解
随机推荐
由ASP.NET Core根据路径下载文件异常引发的探究
He was in '98. I can't play with him
常见电机分类和驱动原理动画[通俗易懂]
Buuctf-- happy New Year
CS231n-2022 Module1: 神经网络要点概述(2)
Highly paid programmers & interview questions: how to ensure the data consistency between redis cache and database in series 117?
By asp Net core downloading files according to the path
IO流总结
Analysis of BlockingQueue source code of AQS
Common motor classification and driving principle animation [easy to understand]
当技术人成长为 CEO,应该修改哪些“Bug”?
PyTorch学习笔记(6)——DataLoader源代码剖析
Buuctf-- connotative software
Fully understand the volatile keyword
np.astype()
Offensive and defensive world re insfsay
区域工业互联网市场成绩单,百度智能云开物第二
BUUCTF--reverse1
Essential for efficient work: how can testers improve their communication skills?
【C语言进阶】动态内存管理