JS去重的几种算法
一. 简单的去重。
利用JSON结构对数组去重。
const arr = [ 1, 2, 3, 3, 4, 5, 2 ] ; let tmp = {} ; let res = [] ; arr.forEach( item => { if( !tmp[item] ) { tmp[item] = item ; res.push( item ) ; } }); console.log( res ) ; //如果不考虑数组顺序与类型 arr.forEach( item => { tmp[item] = item ; }) ; res = Object.keys( tmp ) ; console.log( res ) ;
二. 对相邻重复出现的数组成员去重,每个重复段仅保留一个
如[ 1, 2, 2, 2, 4, 5, 5, 8, 2 ]去重为[ 1, 2, 4, 5, 8, 2 ]
const arr = [ 1, 2, 2, 2, 4, 5, 5, 8, 2 ] ; let res = [] ; let inx = 0 ; arr.forEach( item => { inx = res.length - 1 ; if( inx >= 0 ) { if( item == res[inx] ) { res.pop() ; } } res.push( item ) ; }) ; console.log( res ) ;
扩展为Array静态方法
Array.removeAllDuplicate = function( arr ) { let tmp = {} ; let res = [] ; arr.forEach( item => { if( !tmp[item] ) { tmp[item] = item ; res.push( item ) ; } }); return res ; } Array.removeAdjacentDuplicate = function( arr ) { let res = [] ; let inx = 0 ; arr.forEach( item => { inx = res.length - 1 ; if( inx >= 0 ) { if( item == res[inx] ) { res.pop() ; } } res.push( item ) ; }) ; return res ; }
2018-12-13 10:06:47
2219
0
参与讨论