How to avoid code duplication caused by javascript dict access?

I have two functions that group a list of dicts according to the value of a certain key. Here’s how my array looks:

const sections = [   {     file_id: '1',     heading_level: 4,     readme_file_name: 'Quick.Quick.md',     section_codes: [       1,       3,     ],     section_id: '1',     title: 'Nimble',   },   {     file_id: '1',     heading_level: 2,     readme_file_name: 'Quick.Quick.md',     section_codes: [       3,       4,     ],     section_id: '2',     title: 'Swift Version',   },   // ... ]; 

Some times I need to group the sections by it’s heading_level key value, and other times I need to group by the first value on section_codes array.

I’ve created a single function for each grouping, but the code is exactly the same, except for the line where I access the desired key. So I’ve tried removing duplication, and here’s where I’ve gotten so far:

// Helper func function getValueForKey(key, section) {   const originalValue = section[key];    if (Array.isArray(originalValue)) {     return originalValue[0];   }    return originalValue; }  export function groupSectionsByKey(key, sections) {   const groupedSections = {};    sections.forEach((section) => {     const groupKey = getValueForKey(key, section);     const codeArray = groupedSections[groupKey];      if (codeArray) {       codeArray.push(section);     } else {       groupedSections[groupKey] = [section];     }   });    return groupedSections; } 

This getValueForKey function seems a bit off for me, but I’m not sure if there is a better way to do this. Does anyone have some feedback?

Thanks.