一、使用数组的indexof方法,如果element的index不相等则说明element相同,则过滤掉
Array.prototype.distinct1 = function () {
return this.filter(function (element, index, self) {
return self.indexOf(element) === index;
});
}
二、ES6提供了数据结构Set。类似于数组,但是没有重复值。可以利用Set数据结构中值不能重复的特性去重
var array = []
for( var i in response.data.records){
array.push(response.data.records[i].fieldab);
}
var gyArray = [...new Set(array)];// 得到去重之后的数组
三、遍历两个数组,将原数组的值和新数组的值一一进行比较,如果原数组的值不存在则加入新数组中
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;
}