数组合并及数组去重 对象数组去重

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

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

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

你可能感兴趣的:(数组合并及数组去重 对象数组去重)