JS實現數組去重方法總結
標簽:
JavaScript
话不多说,我们这就进入正文。
第一种:使用forEach从传入参数的下一个索引值开始寻找是否存在重复,如果不存在重复则push到新的数组,达到去重的目的。
noRepeat = (repeatArray) => { var result = []; repeatArray.forEach((value, index ,arr) => { var isNoRepeat = arr.indexOf(value,index+1); if(isNoRepeat === -1){ result.push(value); } }) return result; };
还可以换一种方式实现,利用新数组,遍历要去重的数组,判断通过遍历的数值是否在新数组里面存在,如果不存在,则push到新数组里面。代码如下:
noRepeat = (repeatArray) => { var result = []; repeatArray.forEach((value, index ,arr) => { if (result.indexOf(value) === -1 ) { result.push(value); } }) return result; };
第二种:利用对象的属性不能重复的特点进行去重。
noRepeat = (repeatArray) => { var hash = {}; var result = []; repeatArray.forEach((value, index ,arr) => { if (!hash[value]) { hash[value] = true; result.push(value); } }) return result; };
第三种:先将数组进行排序,然后通过对比相邻的数组进行去重。
noRepeat = (repeatArray) => { repeatArray.sort(); var result = []; repeatArray.forEach((value, index ,arr) => { if (value !== arr[index+1]) { result.push(value); } }) return result; };
第四种:利用ES6的Set新特性(所有元素都是唯一的,没有重复)。需要注意的是,可能存在兼容性问题。
noRepeat = (repeatArray) => { var result = new Set(); repeatArray.forEach((value, index ,arr) => { result.add(value); }) return result; };
该方法处理多个数组的去重是相当的好用,代码如下:
let array1 = [1, 2, 3, 4];let array2 = [2, 3, 4, 5, 6];let noRepeatArray = new Set([... array1, ... array2]);console.log('noRepeatArray:', noRepeatArray);
作者:甜甜_饭
链接:https://www.jianshu.com/p/85ed71e7ddae
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦