1.數(shù)組合并
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擴(kuò)展符...
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]
數(shù)組循環(huán)
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.數(shù)組去重
高階函數(shù)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]
循環(huán):
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.對象數(shù)組去重
高階函數(shù)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}]
循環(huán)
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}]