数组去重
原文:胡哥有话说 https://my.oschina.net/u/4188011/blog/4278961
核心思想,万变不离其宗:
一般创建临时变量tmp,存储不重复的元素(以数组元素存储或对象的键来存储);
遍历待去重数组arr,依次判断tmp中是否包含该元素;
若tmp中不存在该元素,则放入;否则跳过不处理。
方法一
设置tmp为对象,对象的键存储数组元素的值,最终返回对象的所有键。
function array_unique (arr) {
if (arr.length === 0) {
return arr
}
let tmp = {}
let len = arr.length
for (let i = 0; i < len; i++) {
if (tmp[arr[i]] === undefined) {
tmp[arr[i]] = i
}
}
return Object.keys(tmp)
}
// 调用数组去重
let arr = [1, 2, 3, 1, 2]
let newArr = array_unique(arr)
console.log(newArr) // ['1', '2', '3']
缺点
-
你这种方式能区分数字和字符串吗?能区分undefined和’undefined’吗?
-
你现在返回的数据类型还和原有的数据类型一致吗?
方法二
设置tmp为数组,数组中存储唯一的元素,最终返回tmp
function array_unique (arr) {
let len = arr.length
if (!len) {
return []
}
let tmp = []
for (let i = 0; i < len; i++) {
// 判断数组arr的元素是否在数组tmp中
if (tmp.indexOf(arr[i]) === -1) {
tmp.push(arr[i])
}
}
return tmp
}
let arr = [1, 2, 3, '1', 2, undefined, undefined, 'undefined']
let newArr = array_unique(arr)
console.log(newArr) // [1, 2, 3, '1', undefined, 'undefined']
缺点:
- 你这方式能筛选NaN吗?
方法三
原理还是同去重方式二,只不过我们使用ES6的includes替换indexOf方法,includes() 方法,判断数组中是否包含某个元素,如果包含返回true,否则返回false
function array_unique (arr) {
let len = arr.length
if (!len) {
return []
}
let tmp = []
for (let i = 0; i < len; i++) {
// 判断数组arr的元素是否在数组tmp中
if (!tmp.includes(arr[i]) {
tmp.push(arr[i])
}
}
return tmp
}
let arr = [1, 2, 3, '1', 2, undefined, undefined, 'undefined', NaN, NaN]
let newArr = array_unique(arr)
console.log(newArr) // [1, 2, 3, '1', undefined, 'undefined', NaN]
缺点:
- 你的这个筛选方式能区分对象吗?如{}、{a: 1}
方法四
原理同上,我们要继续换一个判断数组是否包含某元素的方法:
findIndex
findIndex查询数组是否包含某元素,如果存在返回元素的索引,否则返回-1。它比indexOf更加先进的地方在于能传入callback,按约定方式查询。
function array_unique (arr) {
let len = arr.length
if (!len) {
return []
}
let tmp = []
for (let i = 0; i < len; i++) {
// 判断数组arr的元素是否在数组tmp中
if (tmp.findIndex((v) => JSON.stringify(v) === JSON.stringify(arr[i])) === -1) {
tmp.push(arr[i])
}
}
return tmp
}
let arr = [1, 2, 3, '1', 2, undefined, undefined, 'undefined', NaN, NaN, {}, {}, {a: 1}, {a: 1}]
let newArr = array_unique(arr)
console.log(newArr) // [1, 2, 3, '1', undefined, 'undefined', NaN, {}, {a: 1}]