Home >Web Front-end >JS Tutorial >What are the methods to achieve array deduplication in js? A brief introduction to js array deduplication method
There are many ways to remove duplicate data from js arrays. Today’s article brings you three methods to remove duplicate data from js arrays. It has certain reference value. Friends in need can refer to it. Hope it helps.
One of the js array deduplication methods: Object simulation HashMap traversal and deduplication
function duplicates(arr) { var newArr=[] var newArr1=[] for(var i = 0;i<arr.length;i++){ for(var j=0;j<arr.length;j++){ if(i!=j){ if(arr[i]==arr[j]){ newArr.push(arr[i]) } } } } var json={} for(var i = 0; i < newArr.length; i++){ if(!json[newArr[i]]){ newArr1.push(newArr[i]); json[newArr[i]] = 1; } } return newArr1 }
The second js array deduplication method: Set the gate flag, according to conditions Deduplication
function duplicates(arr) { var newArr=[] var newArr1=[] for(var i = 0;i<arr.length;i++){ for(var j=0;j<arr.length;j++){ if(i!=j){ if(arr[i]==arr[j]){ newArr.push(arr[i]) } } } } newArr1.push(newArr[0]) for(var i=0;i<newArr.length;i++){ var flag=0 for(var j=0;j<newArr1.length;j++){ if(newArr[i]==newArr1[j]) flag=1 } if(flag==0) newArr1.push(newArr[i]) } return newArr1 }
The third method to deduplicate js arrays: ES6, set collection deduplication
function duplicates(arr) { let newArr = arr; arr = []; let set = new Set(); set(newArr); for (let i of set){ arr.push(i); } return arr; }
Related recommendations:
JS Array Removal of Duplicate Data
JS Array Removal Detailed Graphics and Text
js 4 ways to remove duplication from arrays
The above is the detailed content of What are the methods to achieve array deduplication in js? A brief introduction to js array deduplication method. For more information, please follow other related articles on the PHP Chinese website!