Deduplication of Java Array
- 2021-12-05 06:10:01
- OfStack
Scenario 1 of directory array deduplication, ES6-set2, deduplication using Map data structure 3, nested loop + splice4, forEach + indexOf summary
Scenario of array deduplication
Set the array
var arr =[1,1,‘true',‘true',true,true,66,66,false,false,undefined,undefined, null,null, NaN, NaN, 0, 0, ‘a', ‘a',{},{}]
Filter out duplicate values in
1. ES6-set
Using set in ES6 is the easiest way to remove duplicate
<script>
var arr=[1,2,3,4,1,2,3]
// First, convert the array to set
var set=new Set(arr)
// Again set Convert to an array
console.log(Array.from(set))
</script>
2. Using Map data structure to remove duplicate
Create an empty Map data structure, traverse the array that needs to be deduplicated, and store every element of the array as key into Map. Since the same key value will not appear in Map, the final result is the de-duplication result
function shuzu(arr) {
let map = new Map();
let array = new Array(); // Arrays are used to return results
for (let i = 0; i < arr.length; i++) {
if(map .has(arr[i])) { // If there is a key Value
map .set(arr[i], true);
} else {
map .set(arr[i], false); // If there is no such thing as key Value
array .push(arr[i]);
}
}
return array ;
}
3. Nested Loop + splice
function shuzu(arr){
for(var i = 0 ; i < arr.length; i++){
for( var j = i + 1; j < arr.length; j++){
if( arr[i] === arr[j] ){
arr.splice(j,1);
}
}
}
return arr;
}
4. forEach + indexOf
function shuzu(arr){
var res = [];
arr.forEach((val,index)=>{
if( res.indexOf(val) === -1 ){
res.push(val);
}
});
return res;
}
Summarize
This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!