// 数组去重方法
let arr1 = Array.from(new Array(10000), (item, index) => {
return index;
})
let arr2 = Array.from(new Array(5000), (item, index) => {
return index + index
})
console.log([...arr1, ...arr2])
// 方法一:Array.filter() + indexOf
function distinct(a, b) {
let arr = a.concat(b);
return arr.filter((item, index) => {
return arr.indexOf(item) === index
})
}
// 方法二: for...of + includes()
function distinct(a, b) {
let arr = a.concat(b);
let result = [];
for (let i of arr) {
!result.includes(i) && result.push(i)
}
return result;
}
// 方法三:双重for循环
function distinct(a, b) {
let arr = a.concat(b);
for (let i = 0, len = arr.length; i < len; i++) {
for (let j = i + 1; j < len; j++) {
if (arr[i] === arr[j]) {
arr.splice(j, 1);
len--;
j--;
}
}
}
}
// 方法四:Array.sort()
function distinct(a, b) {
let arr = a.concat(b);
arr.sort(function(a, b) {
return a - b;
})
let result = [arr[0]]
for (let i = 1, len = arr.length; i < len; i++) {
arr[i] !== arr[i - 1] && result.push(arr[i])
}
return result
}
// 方法五:for...of + Object
function distinct(a, b) {
let arr = a.concat(b)
let result = []
let obj = {}
for (let i of arr) {
if (!obj[i]) {
result.push(i)
obj[i] = 1
}
}
return result
}
// 方法六:es6的new set()
function distinct(a, b) {
return Array.from(new Set([...a, ...b]))
}
console.log(distinct(arr1, arr2))
转载自 JS实现数组去重方法整理