方法1:先排序后去重
function removeRepeat1(array) {
var newsArr = [],point;
array.sort();
point = array[0];
newsArr.push(array[0]);
for (var i = 1; i < array.length; i++) {
if (array[i] != point) {
newsArr.push(array[i]);
point = array[i];
}
}
return newsArr;
}
方法2:利用forEach方法遍历数组并使用indexOf判断值的下标是否与当前索引相等
function removeRepeat2(array) {
var newsArr = [];
array.forEach(function(value, i, array) {
if (array.indexOf(value) === i) {
newsArr.push(value);
}
});
return newsArr;
}
方法3:利用json对象保存数据的无序性,判断对象中是否已经存在数组值,若不存在利用object[item]=1去保存,从而实现去重
function removeRepeat3(array) {
var obj = {},newsArr = [];
for (var i = 0, j = array.length; i < j; i++) {
console.log(obj[array[i]]);
if (!obj[array[i]]) {
obj[array[i]] = 1;
newsArr.push(array[i]);
}
}
return newsArr;
}
方法4:利用indexOf(undefined)===-1去重
function removeRepeat4(array) {
var newsArr = [];
for (var i = 0, j = array.length; i < j; i++) {
if (newsArr.indexOf(array[i]) === -1) {
newsArr.push(array[i]);
}
}
return newsArr;
}
方法5:ES6数去重,利用了Set()数据结构其成员的唯一性,再使用Array.from()方法转化为
removeRepeat5(array){
return Array.from(new Set(array));
}