当前位置: 首页 > Web前端 > JavaScript

JavaScript&ES6----数组去重的多种方法

时间:2023-03-27 17:39:18 JavaScript

方法一---双层for循环使用双层for循环,前一项循环,下一项循环,两两比较,if如果发现重复,使用splice()属性从数组中删除重复元素arrletarr=[2,5,1,5,3,2,'hello','1',4]letunique=(arr)=>{//第一层for循环循环数组的前一项for(i=0;i{//声明一个新数组letnewArr=[];for(i=0;i{//声明一个新数组letnewArr=[];for(i=0;i{letobj={}returnarr.filter(function(item,index,arr){//console.log(item);//是arr中的元素returnobj.hasOwnProperty(typeofitem+item)?false:(obj[typeofitem+item]=true)})}console.log(unique4(arr));//[1,'1',2,3,4,5,'hello']方法7-----使用filterletarr=[2,5,1,5,3,2,'hello','1',4]functionunique5(arr){returnarr.filter(function(item,index,arr){//console.log(index);//0123456789//当前元素,原数组第一个索引==当前索引值,否则返回当前elementreturnarr.indexOf(item,0)===index})}console.log(unique5(arr));//[1,'1',2,3,4,5,'hello']方法8-----使用递归去重letarr=[2,5,1,5,3,2,'hello','1',4]functionunique6(arr){arr.sort(function(a,b){returna-b})functionloop(index){if(index>=1){如果(到达[索引]===arr[index-1]){arr.splice(index,1)}//递归循环和数组去重loop(index-1)}}loop(arr.length-1)returnarr}console.log(unique6(arr)));//[1,'1',2,3,4,5,'hello']方法九-----利用Map数据结构去重原理:创建一个空的Map数据结构,遍历需要对于重数组,将数组的每个元素作为键存储在Map中由于相同的key值不会出现在Map中,所以最终结果为去重后的结果//使用Map数据结构去重letarr=[2,5,1,5,3,2,'hello','1',4]functionunique7(arr){letmap=newMap()letnewArr=newArray()for(leti=0;iprev.includes(cur)?prev:[...prev,cur],[])}console.log(unique8(arr));//[1,'1',2,3,4,5,'你好']