<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
init();
var arr, arr1, cut, hashMap;
function init() {
// 方法2辅助变量
cut = '#';
// 方法3辅助变量
hashMap = {};
// 原数组
arr = [1, 3, 2, 5, 2, 4, 1, 3, 4, 6];
// 辅助数组,用于不改变原数组的去重方法
arr1 = [];
// method1();
// method2();
// method3();
// method4();
// method5();
// method6();
// method7();
// method8();
// method9();
//method10();
console.log(arr, arr1);
}
// 数组去重的几种方法
// 方法1 -- 改变原数组
function method1() {
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length;) {
if (arr[i] === arr[j]) {
arr.splice(j, 1);
continue;
}
j++;
}
}
}
// 方法2 -- 改变原数组
function method2() {
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
arr.splice(j, 1);
arr.splice(j, 0, cut);
}
}
}
var i;
while ((i = arr.indexOf(cut)) !== -1) {
if (arr[i] === cut) {
arr.splice(i, 1);
}
}
}
//方法3 -- 改变原数组
function method3() {
for (var i = 0; i < arr.length;) {
if (hashMap[arr[i]] === undefined) {
hashMap[arr[i]] = 1;
} else {
arr.splice(i, 1);
continue;
}
i++;
}
}
//方法4 -- 不改变原数组
function method4() {
arr.forEach(function (item) {
if (hashMap[item] === undefined) {
hashMap[item] = 1;
arr1.push(item);
}
});
}
//方法5 -- 不改变原数组 includesAPI ES6 存在,可能存在兼容性问题
function method5() {
arr.forEach(function (item) {
if (!arr1.includes(item)) {
arr1.push(item);
}
});
}
//方法6 -- 不改变原数组
function method6() {
arr.forEach(function (item) {
if (arr1.indexOf(item) === -1) {
arr1.push(item);
}
});
}
//方法7 -- 不改变原数组
function method7() {
arr.forEach(function (item) {
// 假设所有元素都不重复
var bool = true;
arr1.forEach(function (it) {
if (it === item) {
bool = false;
}
});
if (bool) {
arr1.push(item);
}
});
}
// 方法8 -- 改变原数组
function method8() {
arr.sort(function (a, b) {
return a - b;
});
//关于方法8后面的去重数组,这里用到一个我自创的数组分类下的算法思想--盲人摸硬币。
//盲人只能摸,称量重量,无法通过看来分辨劣币。劣币有1个简单的法则是缺斤少两。
//先让盲人摸1个正常的硬币,然后感受一下重量。
//然后一个桌子铺开所有硬币,盲人的左手先放到桌子的最左边的边缘,
//右边的手放到左手紧邻右边,也就是最左边第一个硬币的位置。右手去感受,如果是劣币,
//右手就不管他,继续下一个硬币。如果右手觉得这个是好币,那么左手先往右进一步,然后
//把右手的硬币"复制"给左边,本次循环结束,继续下次循环。
//数组的新长度是右手摸完后左手的索引+1。
//算法思想:忽略坏的,坏的先让他占着位置。坏的要么被忽略,要么被好的替换。
//这是一种良币驱逐劣币的思路。从这个算法中也可以看到如果管理人才,
//应该采取怎样的策略。
//以及作为打工人,怎样才可以保持一颗平常的心态持续前进。加油,打工人!!!
var i;
for (i = 0, j = 1; j < arr.length; j++) {
if (arr[j] !== arr[j - 1]) {
arr[++i] = arr[j];
}
}
arr.length = i + 1;
}
//方法9 -- 不改变原数组
function method9(){
arr1 = arr.reduce(function (v, t) {
if (v.indexOf(t) === -1) v.push(t);
return v;
}, []);
}
//方法10 -- 不改变原数组
function method10(){
return Array.from(new Set(arr));
}
</script>
</body>
</html>
javascript数组去重的方法
最新推荐文章于 2024-10-05 12:29:44 发布