JS array to remove duplicate data

It workers2022-06-23 18:05:49

1、 Traversal array method

Create a new array , Then loop through the array to be de duplicated , Each time it is judged that the new array does not contain the value of the old array ( For new array indexOf Method retrieves the value of the old array and returns a result equal to -1) Add the value to the new array .

 let oldArr = [1, 2, 3, 4, 5, 5 , 6, 7, 8, 2, 3];
let newArr = unique(oldArr);
function unique(arr){
let hash=[];
for (let i = 0; i < arr.length; i++) {
if(hash.indexOf(arr[i]) === -1){
hash.push(arr[i]);
}
}
return hash;
}

2、 Array subscript judgment

Similar to the first method , First traversal , Then determine the number of the current array i Whether the position of the first occurrence of an item in the array is the same as i equal , If not, it means repetition , Ignore , Do not add new arrays .

 let oldArr = [1, 2, 3, 4, 5, 5 , 6, 7, 8, 2, 3];
let newArr = unique(oldArr);
function unique(arr){
let hash=[];
for (let i = 0; i < arr.length; i++) {
if(arr.indexOf(arr[i]) === i){
hash.push(arr[i]);
}
}
return hash;
}

3、 Judge after sorting

After sorting the array , Compare the last value of the new array with the current value of the old array , If equal, repeat , If not, add to the new array .

 function unique(arr){
arr.sort();
let hash = [arr[0]];
for (let i = 1; i < arr.length; i++) {
if (arr[i] != hash[hash.length-1]) {
hash.push(arr[i]);
}
}
return hash;
}

4、es6 Of Set duplicate removal

Set type :ES6 Provides a new data structure Set. It's like an array , But the values of the members are unique , There are no duplicate values .

Set Itself a constructor , Used to generate Set data structure .

So we can use Set To handle arrays , But it can be used after processing Array.form Method or extension function to convert it back to the array , Otherwise, you will get Set type , For some places with type judgment, it is not passed .

4.1、 Array.from transformation Set The type is Array

 let oldArr = [1, 2, 3, 4, 5, 5 , 6, 7, 8, 2, 3];
let newArr = new Set(oldArr);
console.log(newArr);
console.log(newArr instanceof Array); // Now it's Set type , No Array
newArr = Array.from(newArr);
console.log(newArr instanceof Array);

4.2、 Extended function conversion Set The type is Array

 let oldArr = [1, 2, 3, 4, 5, 5 , 6, 7, 8, 2, 3];
let newArr = [...new Set(oldArr)];

thank
Similar articles

2022-06-23