Looking up another array from d3 joined data

I need to lookup a value in another array based on a key within the data joined to svg within d3.

The d3 joined dataset is boundaries (which contains a key of lad17cd for the local authority) and then I need to look up the population in localAuthorities using the same key.

I’ve tried various ways (using find on local authorities and the [] notation to refer to a key, but for that, I’m not sure how it would know which field is the key), but none seem to work.

Full code is at Carbon Calculator Map / Chris Woods / Observable, with the lookup code towards the bottom of leafletBoundaryMap.

The currently uncommented line refers to a specific value of lad17cd and this works, but obviously I don’t want to hard code it.

Any pointers warmly welcomed.

const areaPaths = g.selectAll('path')
    //.attr("fill", d => localAuthorities[d.properties.lad17cd].population > 100000 ? "#ffe26d" : "#c837ed")
    .attr("fill", localAuthorities.find(d => d.lad17cd === "E06000013").population < 100000 ? "#ffe26d" : "#c837ed")
    //.attr("fill", d => localAuthorities.find(la => la.lad17cd === d.properties.lad17cd).population < 100000 ? "#ffe26d" : "#c837ed")

I made a localIndex object from the from localAuthorities data.
That lets me reference the array of localAuthorities using the key from d.properties.lad17cd

localIndex = {
  let idx = {}
  let idxlo = localAuthorities.map(d => d.lad17cd)
  for (let i = 0; i < idxlo.length; ++i) {
   idx[idxlo[i]]= i
  return idx
    .attr("fill", d =>  localAuthorities[localIndex[d.properties.lad17cd]].population > 100000 ? "#ffe26d" : "#c837ed")

That shows now show a bug because d.properties.lad17cd is trying to find these data points and they are not present in localAuthorities


You may want to use a Map for that:

lad17cd = new Map(localAuthorities.map(d => [d.lad17cd, d]))
1 Like

Thanks @hellonearthis and @mootari. @mootari, am I right in thinking the map creates a new array of key value pairs, with the value being the whole object from the original array? And that you do this as the lookup only works with key value pairs?

@ChrisWoodsSays While the keys in a Map can be arbitrary things, they only work for 1:1 relationships (in case of duplicate keys only the last entry is kept). If you want to create indexes for non-unique keys, I recommend taking a look at d3.group and d3.rollup.