Home >Web Front-end >JS Tutorial >Summary of js array deduplication methods
Sort the array first. After sorting, compare the elements with the previous elements and remove the ones that are the same. This method uses The ones are sort() method and slice()
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j'];//对数组先进行排序arr.sort(); for(var i = 0; i < arr.length; i++) { //用当前的元素与他的前一个元素进行对比 if(arr[i] == arr[i - 1]) { //如果相同的话,就删除掉第i个元素 arr.splice(i, 1); } } console.log(arr);
Traverse the array, define a new array, use indexOf to determine whether it exists in the new array, if not, push to the new array Array, and finally return the new array
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j'];function delArr(array){ var newArr=[];//新建一个新数组 //遍历参数数组array for(var i=0;i<array.length;i++){ //判断新数组是否有这个元素值,没有的话,就把arr[i]给push到新数组newArr中 if(newArr.indexOf(array[i])===-1){ newArr.push(arr[i]); } } return newArr; } console.log(delArr(arr));
Use the object key-value pairing method: create a new js object and a new array, and when traversing the incoming array, determine whether the value is a js object key, if not, add the key to the object and put it into a new array.
Note: When determining whether it is a js object key, "toString()" will be automatically executed on the incoming key. Different keys may be mistaken for the same; for example: a[1], a[ "1"] . To solve the above problem, you still have to call "indexOf".
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j'];function delArr2(array){ var json={},newArr=[],val,type; for(var i=0;i<array.length;i++){ val=array[i]; //判断val是什么数据类型 type=typeof val; console.log("判断类型"+[type]); //判断值是否为js对象的键,不是的话给对象新增该键并放入新数组 if(!json[val]){ json[val]=[type]; newArr.push(val); } else if(json[val].indexOf(type)<0){ json[val].push(type); newArr.push(val); } } return newArr; } console.log(delArr2(arr));
The above is the detailed content of Summary of js array deduplication methods. For more information, please follow other related articles on the PHP Chinese website!