保留数组非重复元素
const arr = [1, 3, 3, 6, 2, 2, 4, 4, '1']
let arr1 = []
console.time('使用indexOf和lastIndexOf')
arr.forEach(element => {
if (arr.indexOf(element) === arr.lastIndexOf(element)) arr1.push(element)
})
console.timeEnd('使用indexOf和lastIndexOf')
console.log('使用indexOf和lastIndexOf', arr1)
let arr2 = []
console.time('双层for循环')
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (i === j) continue
if (arr[i] === arr[j]) break
if (j === arr.length - 1) arr2.push(arr[i])
if (j === arr.length - 2 && i === arr.length - 1) arr2.push(arr[i])
}
}
console.timeEnd('双层for循环')
console.log('双层for循环', arr2)
使用indexOf和lastIndexOf: 0.167ms
使用indexOf和lastIndexOf [ 1, 6, '1' ]
双层for循环: 0.065ms
双层for循环 [ 1, 6, '1' ]
保留数组重复元素
const arr = [1, 3, 3, 6, 2, 2, 4, 4, '1']
let arr1 = []
console.time('使用indexOf和lastIndexOf')
arr.forEach(element => {
if (arr1.indexOf(element) !== -1) return
if (arr.indexOf(element) !== arr.lastIndexOf(element)) arr1.push(element)
})
console.timeEnd('使用indexOf和lastIndexOf')
console.log('使用indexOf和lastIndexOf', arr1)
let arr2 = []
console.time('双层for循环')
for (let i = 0; i < arr.length; i++) {
if (arr2.indexOf(arr[i]) !== -1) continue
for (let j = 0; j < arr.length; j++) {
if (i === j) continue
if (arr[i] === arr[j]) {
arr2.push(arr[i])
break
}
}
}
console.timeEnd('双层for循环')
console.log('双层for循环', arr2)
使用indexOf和lastIndexOf: 0.217ms
使用indexOf和lastIndexOf [ 3, 2, 4 ]
双层for循环: 0.052ms
双层for循环 [ 3, 2, 4 ]