1、数组去重,简单方法!适合数组内没有对象
export function unique(data) { // 先扁平化数组,再去重 const arr=data.join().split(',') return Array.from(new Set(arr)) }
注明:适合纯数组
2、对象内数组去重和数组内数组去重,举例
// 适合如下三种情况 let z = { s: ['1', '2', '3'], b: ['2', '3', '4'] } let x=['2', '3', '4',['1', '2', '3'] ] let y = { s: [{a:2}, {a:3}, {a:4}], b:[{a:3}, {a:6}, {a:5}], }
注意如下的扁平化方法,只是展示不同的扁平化,可以自行选择适合的用!
第一种
let obj = { s: ['1', '2', '3'], b: ['2', '3', '4'] } let arr = Object.values(obj).flat() // 扁平化方法1 arr.reduce(function (item, next) { item.includes(next) ? '' : item.push(next); return item; }, []); => ["1", "2", "3", "4"]
第二种
let arr=['2', '3', '4',['1', '2', '3'] ] arr=arr.join().split(',')//扁平化 arr.reduce(function (item, next) { item.includes(next) ? '' : item.push(next); return item; }, []); => ["1", "2", "3", "4"]
第三种
let obj = { s: [{a:2}, {a:3}, {a:4}], b:[{a:3}, {a:6}, {a:5}], } let arr = Object.keys(obj).map(key => obj[key]).flat() function reduce(arr){ let obj={} return arr.reduce(function (item, next) { obj[next.a] ? '' : obj[next.a] = true && item.push(next); return item; }, []); } reduce(arr)
下面为扁平化的四种方法
// 这个其实只会获取到所有最后一级的 function flatten(arr) { return arr.reduce((result, item) => { return result.concat(Array.isArray(item) ? flatten(item) : item); }, []); } // 下面这个会获取到每一级的value function flatten(arr) { return arr.reduce((result, item) => { console.log(item.children) result.concat(item.value) return result.concat(Array.isArray(item.children) && item.children.length>0 ? this.flatten(item.children).concat(item.value) : item.value); }, []); }, let arr = Object.keys(obj).map(key => obj[key]).flat() let arr = Object.values(obj).flat() let arr=arr.join().split(',')//扁平化