Adding column from one array to another based on key

Say I have two arrays:

a = [
{ name: “Texas”,
pop: 15000},
{ name: “California”,
pop: 45000},
{ name: “Alaska”,
pop: 5000}
]
b = [
{ name: “Texas”,
deaths: 2000},
{ name: “California”,
deaths: 1000},
{ name: “Alaska”,
deaths: 500}
]
Like so and I am trying to add a deaths column to the “a” array based on the name being the key.
So the completed array would look like:
a = [
{ name: “Texas”,
pop: 15000,
deaths: 2000},
{ name: “California”,
pop: 45000
deaths: 1000},
{ name: “Alaska”,
pop: 5000,
deaths:500}
]

so I attempt:

a.map(d => ({
name: d.name,
pop: d.pop,
deaths: d.filter((b => b.name) === d.name)).deaths
})) //but this just throws a “not a function error”

and deaths: b.map(d => d.deaths) //this creates the column but maps the entire array to each object no
//filtering based on the name field…

Is there an easier way to accomplish this? Am I even on the right track? Any and all help is appreciated, I would like to learn how to manipulate the data inside of observable instead of just going into the datasheets and manually creating these columns…

Hi - I think your filter function is mixing up some of the variables. Something like the following should work.

a.map(d => ({
name: d.name,
pop: d.pop,
deaths: b.filter(e =>e.name === d.name)[0].deaths
}))

The main difference is to remember that you are filtering on the b array and that filter always returns an array (so you need an index).

More generally, you might consider using a javascript Map for one of the arrays, say, b. That way you are just looping through the a array and doing a bunch of Map lookups instead of looping over b again and again, which should be more efficient,e.g.,

deathLookup = new Map(b.map(d=>[d.name, d.deaths]))
...
a.map(d => ({
name: d.name,
pop: d.pop,
deaths: deathsLookup.get(d.name)
}))

I love Maps and use them all the time for this sort of thing!

Hope this helps.

-Evan

1 Like

Thank you Evan, you are a saint.