Case requirements:
If there are the following two user arrays, filter out those with the same user ID and merge them into a new array
let users1 = [
{
id:1, name:'tom', age: 20},
{
id:2, name:'jack', age: 21},
{
id:3, name:'smith', age: 22}
]
let users2 = [
{
id:3, name:'smith', age: 22},
{
id:4, name:'rose', age: 23},
{
id:5, name:'tina', age: 24},
]
after the merger
[
{
id:1, name:'tom', age: 20},
{
id:2, name:'jack', age: 21},
{
id:3, name:'smith', age: 22},
{
id:4, name:'rose', age: 23},
{
id:5, name:'tina', age: 24},
]
accomplish
First use ... to merge into a new array, and then use the reduce method to remove the values with the same id in the object
let newArr = [...users1, ...users2]
let obj = {
}
let newUsers = newArr.reduce((item, next) => {
obj[next.id] ? '' : obj[next.id] = true && item.push(next)
return item
}, [])