1、先排序,在让相邻元素对比去重
const nums = [3, 1, 1, 5, 2, 3, 4, 3, 5, 5, 6, 4, 6, 6, 6]; Array.prototype.arrayNorepeat = function () { let arr = this; let len = arr.length - 1; let i = 0; //先给数组排序 for (; i < len; ++i) { let j = 0; for (; j < len - i; ++j) { if (arr[j] > arr[j + 1]) { arr[j] = arr[j] + arr[j + 1]; arr[j + 1] = arr[j] - arr[j + 1]; arr[j] = arr[j] - arr[j + 1]; } } } //对数组进行去重 for (i = 0; i < arr.length; ++i) { if (arr[i] === arr[i + 1]) { arr.splice(i, 1); //一旦相邻两个元素相等,外层循环的初始值从0开始 i = -1; } } return arr; } console.log(nums.arrayNorepeat());
2、直接去重(排序方式是按照初始的排序方式)
const nums = [3, 1, 1, 5, 2, 3, 4, 3, 5, 5, 6, 4, 6, 6, 6]; Array.prototype.arrayNorepeat = function () { let arr = this; let i = 0; for (; i < arr.length; ++i) { let j = 0; for (; j < arr.length; ++j) { if (i != j) { if (arr[i] === arr[j]) { //如果你想保留最后一个重复的数字,把splice方法的j改成i就可以了 arr.splice(j, 1); //一旦相邻两个元素相等,外层循环的初始值从0开始 i = -1; } } } } return arr; } console.log(nums.arrayNorepeat());
原文地址:https://www.cnblogs.com/onebox/p/8110904.html
时间: 2024-10-13 10:07:14