方法1:普通版,利用indexOf去重
新建一个数组,遍历去要重的数组,当值不在新数组的时候(indexOf为-1)就加入该新数组中。
- indexOf() 方法:返回某个指定的字符串值在字符串中首次出现的位置。如果要检索的字符串值没有出现,则该方法返回 -1。
//方法1:普通版,利用indexOf去重
function arrayUnique(arr){
var len = arr.length;
var res = [];
for(var i = 0; i < len; i++) {
if(res.indexOf(arr[i]) === -1) { //如果该数之前没有出现过
res.push(arr[i]); //就把该元素push进去
}
}
return res;
}
var arr = [1, 1, 'hi', 'true', 'true', true, 15, 15, 15];
console.log(arrayUnique(arr)); //[ 1, 'hi', 'true', true, 15 ]
方法2:利用Map去重
创建一个空Map数据结构,遍历需要去重的数组,把数组的每一个元素作为key存到Map中。由于Map中不会出现相同的key值,所以最终得到的就是去重后的结果。
Map是ES6 提供的新的数据结构。
Map 对象保存键值对。任何值(对象或者原始值) 都可以作为一个键或一个值。以下是Map对象的方法:
// 方法2:hashMap
function arrayUnique2(arr) {
let res = []; // 结果数组
let map = new Map();
for (let i = 0; i < arr.length; i++) {
if(!map.get(arr[i])) { //若果hashMap中还没有该key值
map.set(arr[i], 1);
res.push(arr[i]);
}
}
return res;
}
var arr = [1, 1, 'hi', 'true', 'true', true, 15, 15, 15];
console.log(arrayUnique2(arr)); //[ 1, 'hi', 'true', true, 15 ]
方法3:利用Set去重
Array.from( set对象 ) 可以把set转成数组。
ES6 新增了 Set 这一数据结构,类似于数组,区别在于它所有的成员都是唯一的,不能有重复的值
- Array.from() 方法:从一个类似数组或可迭代的对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等) 中创建一个新的数组实例。
语法:
Array.from(arrayLike[, mapFn[, thisArg]])
示例代码:
const bar = ["a", "b", "c"];
Array.from(bar);
// ["a", "b", "c"]
Array.from('foo');
// ["f", "o", "o"]
//方法3:使用 Set 进行数组去重
// 使用 Set 完成 数组去重,只能去除字符串和数字的重复,不能去除对象的重复
function uniqueSet(array) {
return Array.from(new Set(array));
}
//或
function uniqueSet2(array) {
return [...new Set(array)]; // 用...(展开操作符)操作符将Set转换为Array
// 用 [...A] 将 A 转换为数组
}
var arr = [1, 1, 'hi', 'true', 'true', true, 15, 15, 15];
console.log(uniqueSet(arr)); //[ 1, 'hi', 'true', true, 15 ]
方法4:使用 filter
将两个数组拼接为一个数组,然后使用 ES6 中的 Array.filter() 遍历数组,并结合 indexOf 来排除重复项。
- filter() 方法:创建一个新的数组,新数组中的元素 是 通过检查 指定数组 中 符合条件的所有元素。
- indexOf() 方法:可返回某个指定的字符串值在字符串中首次出现的位置。
语法
array.filter(function(currentValue,index,arr), thisValue)
参数说明:
语法
array.indexOf(item,start)
参数值
参数 | 描述 |
---|---|
item | 必须。查找的元素。 |
start | 可选的整数参数。规定在数组中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。 |
// 方法4:使用 filter
function uniqueFilter(arr) {
var res = arr.filter(function(item, index, array) {
// 从数组0位开始查,如果当前元素在原始数组中的第一个索引 === 当前索引值,说明它是第一次出现
return array.indexOf(item) === index;
});
return res;
}
var arr = [1, 1, 'hi', 'true', 'true', true, 15, 15, 15];
console.log(uniqueFilter(arr)); //[ 1, 'hi', 'true', true, 15 ]
方法5和方法6
// 方法5:原型方法
Array.prototype.unique = function () {
const newArray = [];
this.forEach(item => {
if (newArray.indexOf(item) === -1) {
newArray.push(item);
}
});
return newArray;
}
// 方法6:精简版 使用 filter 和 indexOf 结合实现
Array.prototype.unique = function () {
return this.filter((item, index) => {
return this.indexOf(item) === index;
})
}