黑马程序员技术交流社区
标题: JavaScript数组去重 [打印本页]
作者: JoyZhang 时间: 2020-12-29 16:58
标题: JavaScript数组去重
一、双重循环去重[JavaScript] 纯文本查看 复制代码
let arr = [1, 3, 2, 3, 6, 8, 9, 7, 12, 7, 8, 9]
function unique(arr) {
if (!Array.isArray(arr)) {
console.log('type is not Array')
return
}
let newArr = []
for (let i = 0; i < arr.length; i++) {
let isRepeat = false
for (let j = 0; j < newArr.length; j++) {
if (arr === newArr[j]) {
isRepeat = true
break
}
}
if (isRepeat) continue
newArr.push(arr)
}
return newArr
}
let a1 = unique(arr)
console.log(a1) // [1, 3, 2, 6, 8, 9, 7, 12]
二、indexOf去重
[JavaScript] 纯文本查看 复制代码
let arr = [1, 3, 2, 3, 6, 8, 9, 7, 12, 7, 8, 9]
function unique(arr) {
if (!Array.isArray(arr)) {
console.log('type is not Array')
return
}
let newArr = []
for (let i = 0; i < arr.length; i++) {
if (newArr.indexOf(arr) !== -1) continue
newArr.push(arr)
}
return newArr
}
let a1 = unique(arr)
console.log(arr) // [1, 3, 2, 3, 6, 8, 9, 7, 12, 7, 8, 9]
console.log(a1) // [1, 3, 2, 6, 8, 9, 7, 12]
三、set去重(ES6)
[JavaScript] 纯文本查看 复制代码
let arr = [1, 3, 2, 3, 6, 8, 9, 7, 12, 7, 8, 9]
let a1 = [...new Set(arr)]
console.log(a1) // [1, 3, 2, 6, 8, 9, 7, 12]
四、filter + indexOf去重
[JavaScript] 纯文本查看 复制代码
let arr = [1, 3, 2, 3, 6, 8, 9, 7, 12, 7, 8, 9]
let a1 = arr.filter((e,i) => arr.indexOf(e) === i)
console.log(a1) // [1, 3, 2, 6, 8, 9, 7, 12]
五、includes去重(ES6)
[JavaScript] 纯文本查看 复制代码
let arr = [1, 3, 2, 3, 6, 8, 9, 7, 12, 7, 8, 9]
function unique(arr) {
let newArr = []
arr.forEach(v => {
if (!newArr.includes(v)) {
newArr.push(v)
}
})
return newArr
}
let a1 = unique(arr)
console.log(a1) // [1, 3, 2, 6, 8, 9, 7, 12]
六、reduce去重
[JavaScript] 纯文本查看 复制代码
let arr = [1, 3, 2, 3, 6, 8, 9, 7, 12, 7, 8, 9]
let newArr = arr.reduce((accumulator,currentValue) => {
if (accumulator.indexOf(currentValue) === -1) {
accumulator.push(currentValue)
}
return accumulator
},[])
console.log(newArr) // [1, 3, 2, 6, 8, 9, 7, 12]
七、数组中包含对象的去重
[JavaScript] 纯文本查看 复制代码
let arr = [
{ name: 'zs', age: 18 },
{ name: 'ls', age: 19 },
{ name: 'zs', age: 19 },
{ name: 'zs', age: 18 }
]
// 数组中嵌套对象,根据对象的某个字段进行对象去重
//arr为数组,u_key为去重依据的字段
function unique(arr, u_key) {
if (!Array.isArray(arr)) {
console.log('type is not Array')
return
}
let map = new Map()
arr.forEach((item, index) => {
if (!map.has(item[u_key])) {
map.set(item[u_key], item)
}
})
return [...map.values()]
}
console.log(unique(arr, 'name')) // [{name: 'zs', age: 18},{name: 'ls', age: 19}]
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |