[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
直接上代码
<script> let arr = [2, 3, 4, 4, 6, 66, 4, 743, 243, 22, 2, 4]; //
一、遍历数组法,新建一个数组,遍历原数组,如果不存在就存入新数组中,最后输出新数组 function first(arr) { let array = []
for (let i = 0; i < arr.length; i++) { if (array.indexOf(arr[i]) == -1) {
array.push(arr[i]) } } return array; } // 排序后相邻去除,排序后对原数组进行遍历,如果与新数组的length -
1的值不同,就添加到新数组中最后输出新数组 function sortNum(a, b) { return a - b; } function
second(arr) { arr.sort(sortNum) let array = [arr[0]] for (let i = 0; i <
arr.length; i++) { if (arr[i] != array[array.length - 1]) { array.push(arr[i])
} } return array; } // 优化遍历数组法(推荐) function third(arr) { let array = []; for
(let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) { ++i } } array.push(arr[i]); } return array; } // ES6
set,set方法由ES6提供,里面的值都是唯一的 function setArr(arr) { let es6Set = new Set(arr)
return [...es6Set]; } console.log('遍历数组法') console.log(first(arr))
console.log('排序后相邻去除法') console.log(second(arr)) console.log('ES6 set')
console.log(setArr(arr)) console.log('优化遍历数组法') console.log(third(arr))
</script>
数组去重并排序
let arr1 = [1, 25, 2, 26, 1234, 6, 213]; let arr2 = [2, 6, 2134, 6, 31, 623];
let c = [...new Set([...arr1, ...arr2])].sort((a, b) => { return a - b; });
//(10) [1, 2, 6, 25, 26, 31, 213, 623, 1234, 2134]