本文共 2880 字,大约阅读时间需要 9 分钟。
新建一个数组,遍历去要重的数组,当值不在新数组的时候(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 ]
创建一个空Map数据结构,遍历需要去重的数组,把数组的每一个元素作为key存到Map中。由于Map中不会出现相同的key值,所以最终得到的就是去重后的结果。
Map是ES6 提供的新的数据结构。
Map 对象保存键值对。任何值(对象或者原始值) 都可以作为一个键或一个值。以下是Map对象的方法:// 方法2:hashMapfunction 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 ]
Array.from( set对象 ) 可以把set转成数组。
ES6 新增了 Set 这一数据结构,类似于数组,区别在于它所有的成员都是唯一的,不能有重复的值
语法:
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 ]
将两个数组拼接为一个数组,然后使用 ES6 中的 Array.filter() 遍历数组,并结合 indexOf 来排除重复项。
array.filter(function(currentValue,index,arr), thisValue)
参数说明:
array.indexOf(item,start)
参数 | 描述 |
---|---|
item | 必须。查找的元素。 |
start | 可选的整数参数。规定在数组中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。 |
// 方法4:使用 filterfunction 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:原型方法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; })}