方法一
使用数组的 indexof 方法, 如果 element 的 index 不相等则说明 element 相同, 则过滤掉
- Array.prototype.distinct1 = function () {
- return this.filter(function (element, index, self) {
- return self.indexOf(element) === index;
- });
- }
方法二
ES6 提供了数据结构 Set. 类似于数组, 但是没有重复值. 可以利用 Set 数据结构中值不能重复的特性去重
- Array.prototype.distinct2 = function () {
- let set = new Set(this);
- return [...set];
- }
方法三
遍历两个数组, 将原数组的值和新数组的值一一进行比较, 如果原数组的值不存在则加入新数组中
- Array.prototype.distinct3 = function () {
- let result = [];
- for (let i of this) {
- let flag = 0;
- for (let j of result) {
- if (i === j) {
- flag = 1;
- }
- }
- if (flag === 0) {
- result.push(i);
- }
- }
- return result;
- }
方法四
先将数组进行排序, 然后遍历数组, 将数组中每个值与其后一个值比较, 如果不同则存入新数组
- Array.prototype.distinct4 = function () {
- var arr = this.sort();
- var result = [];
- for (let i = 0; i < arr.length; i++) {
- if (arr[i] != arr[i + 1])
- result.push(arr[i]);
- }
- return result;
- }
方法五
JS 中数组也是对象, 可以根据对象属性的特性. 遍历数组, 如果该值不是对象的属性, 则在对象中添加等于该值的属性, 并且同时把该值加入新数组
- Array.prototype.distinct5 = function () {
- let result = [];
- let obj = {};
- for (let x of this) {
- if (!obj[x]) {
- obj[x] = x;
- result.push(x);
- }
- }
- return result;
- }
方法六
双重循环遍历数组, 如果值相同, 使用 splice 方法删去后一个相同的值
- Array.prototype.distinct6 = function () {
- let arr = this;
- for (let i = 0; i < arr.length; i++) {
- for (let j = i + 1; j < arr.length; j++) {
- if (arr[i] === arr[j]) {
- arr.splice(j, 1);
- j--;
- }
- }
- }
- return arr;
- }
以上六种方法均可以实现数组去重, 区别是性能不同, 并且有的方法会改变数组的顺序.
来源: http://www.jianshu.com/p/f2d0d4a3c6f5