数组合并及数组去重 对象数组去重
2019-04-01 本文已影响0人
磨人的磨磨虫
1.数组合并
concat方法
let testData=[1,2,3,4,5]
let newData=testData.concat(6,7)
let hotData=newData.concat(testData)
console.log(newData)//[1,2,3,4,5,6,7]
console.log(hotData)//[1,2,3,4,5,6,7,1,2,3,4,5]
es6扩展符...
let testData=[1,2,3,4,5]
let newData=[...testData,6,7]
let hotData=[...newData,...testData]
console.log(newData)//[1,2,3,4,5,6,7]
console.log(hotData)//[1,2,3,4,5,6,7,1,2,3,4,5]
数组循环
let testData=[1,2,3,4,5]
let item=[6,7]
let newData=testData
for(let i=0;i<item.length;i++){
newData.push(item[i])
}
console.log(newData)//[1,2,3,4,5,6,7]
2.数组去重
高阶函数reduce:
let testData=[1,2,3,4,5,1,3]
let newData=testData.reduce((prev,cur)=>{
return prev.indexOf(cur)===-1&&prev.push(cur)
},[])
console.log(newData)//[1, 2, 3, 4, 5]
es6 filter()方法:
let testData=[1,2,3,4,5,1,3]
let newData=testData.filter((v,index,self)=>self.indexOf(v)===index)
console.log(newData)//[1, 2, 3, 4, 5]
es6 new Set() 和 Array.from():
let testData=[1,2,3,4,5,1,3]
let newData=Array.from(new Set(testData))
console.log(newData)//[1, 2, 3, 4, 5]
循环:
let testData=[1,2,3,4,5,1,3]
let newData=[]
for(let i=0;i<testData.length;i++){
let item=testData[i]
let l=newData.indexOf(item)
if(l===-1){
newData.push(item)
}
}
console.log(newData)//[1, 2, 3, 4, 5]
3.对象数组去重
高阶函数reduce
let testData=[
{a:'小花',id:2},
{a:'小明',id:2},
{a:'小巧',id:3},
]
let vessel={}
let newData=testData.reduce((prev,cur,curIndex,curSelf)=>{
vessel[cur['id']]?"":vessel[cur['id']]=true&&prev.push(cur)
return prev
},[])
console.log(newData)//[{a:'小花',id:2},{a:'小巧',id:3}]
循环
let testData=[
{a:'小花',id:2},
{a:'小明',id:2},
{a:'小巧',id:3},
]
let vessel={}
let newData=[]
for(let i=0;i<testData.length;i++){
if(!vessel[testData[i]['id']]){
vessel[testData[i]['id']]=true
newData.push(testData[i])
}
}
console.log(newData)//[{a:'小花',id:2},{a:'小巧',id:3}]