<script>
//双层循环,外层循环元素,内层循环时比较值如果有相同的值则跳过,不相同则push进数组
let arr1 = [1, 1, 2, 3, 5, 43, 3, 4, 3, 5, 3, 5, '5']
Array.prototype.zhuanHuan1 = function () {
let result1 = [];
for (let i = 0; i < arr1.length; i++) {
for (let j = i + 1; j < arr1.length; j++) {
if (arr1[i] == arr1[j]) {
j = ++i;
}
}
result1.push(arr1[i]);
}
return result1;
}
console.log(arr1.zhuanHuan1())
// 方法二:利用splice直接在原数组进行操作双层循环,外层循环元素,内层循环时比较值值相同时,则删去这个值注意点:删除元素之后,需要将数组的长度也减1.
let arr2 = [1, 1, 2, 3, 5, 43, 3, 4, 3, 5, 3, 5, '5'];
Array.prototype.zhuanHuan2 = function () {
let len2 = arr2.length;
for (let i = 0; i < len2; i++) {
for (let j = i + 1; j < len2; j++) {
if (arr2[i] == arr2[j]) {
arr2.splice(j, 1);
len2--;
j--;
}
}
}
return arr2
}
console.log(arr2.zhuanHuan2())
// 方法三:利用对象的属性不能相同的特点进行去重
let arr3 = [1, 1, 2, 3, 5, 43, 3, 4, 3, 5, 3, 5, '5'];
Array.prototype.zhuanHuan3 = function () {
let len3 = arr3.length,
obj = {},
result3 = [];
for (let i = 0; i < len3; i++) {
if (!obj[arr3[i]]) {//如果能查找到,证明数组元素重复了,相反则添加
obj[arr3[i]] = 1;
result3.push(arr3[i])
}
}
return result3;
}
console.log(arr3.zhuanHuan3())
// es6 Set
// Set数据结构,它类似于数组,其成员的值都是唯一的。
let arr4 = [1, 1, 2, 3, 5, 43, 3, 4, 3, 5, 3, 5, '5'];
// 利用Array.from将Set结构转换成数组
function dedupe(array) {
return Array.from(new Set(array));
}
console.log(dedupe(arr4))
// 拓展运算符(...)内部使用for...of循环
let resultarr = [...new Set(arr4)];
console.log(resultarr);
</script>
数组合并并去重
// 一、concat数组拼接,然后再调用排序方法
let arr1 = [1, 2, 3, 4, 23, 4, 5, 23, 4],
arr2 = [1, 2, 3, 5, 23, 34, 5, 2, 3, 5, 3, 2, 4, 5, 3],
newArr = [];
newArr = arr1.concat(arr2);
console.log(newArr);
let result = [...new Set(newArr)];
console.log(result);
// 二、Array.prototype.push.apply()
console.log(Array.prototype.push.apply(arr1, arr2));
//等效于:a.push.apply(a, b);
//也等效于[].push.apply(a, b);
function concatArray(arr1, arr2) {
Array.prototype.push.apply(arr1, arr2);
let result = [...new Set(arr1)];
return result;
}
console.log(concatArray(arr1,arr2))