Join a JSON object of arrays and reduce down to one key Given that I have a dataset as follows:

{ 1: ['Extremely Tall'], 2: ['Tall'], 3: ['Medium', 'Low'], 4: ['Dwarf'] }


and I receive a value (e.g. Tall or Medium) I want to determine the associated key. By the way feel free to change the dataset, i.e. it doesn't have to be a json object... so long as:

Medium -&gt; 3
Low -&gt; 3
Tall -&gt; 2


My solution is below, anyone have a better way of doing it?  

const R = require('ramda')
const heightsMap = { 1: ['Extremely Tall'], 2: ['Tall'], 3: ['Medium', 'Low'], 4: ['Dwarf'] }
const height = 'Medium'

const associatedNumber = R.keys(heightsMap).filter(key =&gt; heightsMap[key].includes(height))[0]

console.log(associatedNumber)
Review

I'm not a big fan of importing other libraries when a built-in alternative is available.


const R = require('ramda')



R.keys could be replaced by Object.keys:

const associatedNumber = Object.keys(heightsMap)
  .filter(key =&gt; heightsMap[key]
  .includes(height))[0]


Two improvements can be made. First, you're using filter which iterates all elements. This is a pity, since you're only interested in the first item [0]. Find is the method you were looking for. Second, You're traversing keys to perform another lookup heightsMap[key]. This could be done in a single iteration using Object.entries.

Proposed Rewrite

const associatedNumber = Object.entries(heightsMap)
  .find(([key, value]) =&gt; value.includes(height))[0];

console.log(associatedNumber);


Note that [0] in the refactored code gets the key of [key, value].