js 数组去重

<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))

 

原文链接:https://www.jb51.net/article/118657.htm

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值