// 改方法可去重 合并
var arrA = [
{ id: 1, name: '张三' },
{ id: 1, name: '张三' },
{ id: 2, name: '李四' },
{ id: 1, age: 12 },
{ id: 1, age: 12 },
{ id: 2, age: 18 }
]
let newArr = arrA.reduce((ret, item) => {
if (ret.some(rei => { return rei.id === item.id })) {
ret.forEach(o => {
if (o.id === item.id) {
Object.assign(o, item)
}
})
return ret
}
return ret.concat(item)
}, [])
//console.log(newArr)
// 递归深拷贝
var obj = {
name: 'Mr.YANG',
sex: '男',
age: 18,
arr: [12, 34, 56, 78, 90],
arrb: [
{id:1},
{id:2},
{id:3},
{id:4},
{id:5}
],
body: {
height: '180cm',
weight: '70kg'
}
}
function deepClone(obj) {
var newObj = null
if (typeof (obj) === 'object' && typeof (obj) !== null) {
newObj = obj instanceof Array ? [] : {}
for (var i in obj) {
newObj[i] = deepClone(obj[i])
}
} else {
newObj = obj
}
return newObj
}
//console.log(deepClone(obj))
var deepArr = [1, 2, [3, 4, [5, 6]], 7, [8, 9, [10]]]
function handArr(arr) {
return arr.reduce((ret, item) => {
return ret.concat(Array.isArray(item) ? handArr(item) : item)
}, [])
}
// 数组扁平化与去重
var beforArr = [1, 2, [3, 4, 5, 1, [2, 5, 6, [7, 5, 6]]], 8, [9, 3], 10]
function handArr(arr) {
return arr.reduce((ret, item) => {
return ret.filter((itm, index, arry) => { return arry.indexOf(itm) === index }).concat(Array.isArray(item) ? handArr(item) : item)
}, [])
}
// console.log(handArr(beforArr))
//取平均值
var countArr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
function handCount(arr) {
return arr.reduce((ret, item, index, restArr) => {
if(index === restArr.length - 1){
return ret / restArr.length
}
return ret + item
}, 0)
}
// console.log(handCount(countArr))
console