Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concating two arrays into one

Tags:

javascript

I am looking to combine these two arrays into a single one. I want any id information that is the same to be filtered so that it only appears once, making it a simple list of name, age, occupation, and address.

I have tried simply concating the info, using splice, using filter... but I just cant seem to get the right answer.

var a = [{
  id: 'aBcDeFgH',
  firstName: 'Juan',
  lastName: 'Doe',
  age: 32
 },
{
  id: 'zYxWvUt',
  firstName: 'Alex',
  lastName: 'Smith',
  age: 24
}]


var b = [{
  id: 'aBcDeFgH',
  occupation: 'architect',
  address: {
    street: '123 Main St',
    city: 'CityTown',
    Country: 'USA'
  }
},
{
  id: 'zYxWvUt',
  occupation: 'receptionist',
  address: {
    street: '555 Ocean Ave',
    city: 'Beach City',
    Country: 'USA'
  }
}]

I always end up with a single list after the concat, but I cant find out how to filter the same info.

like image 928
GunarsAuskaps Avatar asked Jul 08 '19 14:07

GunarsAuskaps


1 Answers

Sounds like you need to merge each item of each array together - and that they're both in the same order, in which case you could do:

const newList = []

a.forEach((item, index) => {
  newList.push({
    ...item,
    ...b[index]
  })
})

console.log(newList)
like image 74
Huw Davies Avatar answered Oct 25 '22 19:10

Huw Davies