Array deduplication is a common scenario in business development. This paper summarizes several ideas of data deduplication implementation.

1. With the help of the Set

/** * use Map ** /
const arr = [12.34.565.12.34.1.3.1]
// const newArr = [...new Set(arr)] 
const newArr = Array.from(new Set(arr))

console.log('newArr',newArr);
Copy the code

Case Effect:

2. Routine operations

/ const arr = [12,34,565,12,34,1,3,1] const newArray = []; arr.forEach(item => { if(newArray.indexOf(item) === -1){ newArray.push(item) } }); console.log('newArray', newArray)Copy the code

Case Effect:

3. Use objects

Const arr = [12,34,565,12,34,1,3,1] const obj = {}; for (let index = 0; index < arr.length; index++) { const item = arr[index]; if(obj[item] === undefined){ obj[item] = item; }else{ arr.splice(index, 1); index--; }} console.log(' implemented with object ', arr);Copy the code

Case Effect:

4. Sort and use the regex power

*/ const arr = [12,34,565,12,34,1,3] const sortArr = arr.sort((a, b)=> a-b) console.log('sortArr', sortArr); const sortArrStr = sortArr.join('@') + '@'; console.log('sortArrStr', sortArrStr); const reg = /(\d+@)\1*/g; const newArr = []; sortArrStr.replace(reg, (val, group)=>{ console.log('val', val); console.log('group', group); newArr.push(parseInt(group)) }) console.log('newArr', newArr);Copy the code

Effect:

5. Skillfully filter using filter and indexOf

/** * const arr = [12,34,565,12,34,1,3,1] const result = arr. Filter ((item, index)=>{ return arr.indexOf(item) === index; }) console.log('result', result);Copy the code

Effect:

conclusion

This paper summarizes several ways to achieve array de-duplication by means of Set, general operation, object, sort and regular ability, filter and so on.

If it is helpful to you, welcome to give the author a thumbs-up and attention haha ~