A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© JoyZhang 中级黑马   /  2020-12-29 16:58  /  2030 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

一、双重循环去重
[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[i] === newArr[j]) {
				isRepeat = true
				break
			}
		}
		if (isRepeat) continue
		newArr.push(arr[i])
	}
	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[i]) !== -1) continue
		newArr.push(arr[i])
	}
	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}]


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马