Search code examples
javascriptarraysdictionaryfilter

Create array of values from a dictionary of array of objects filtered by property


I have a dictionary where key is string and value is array of objects:

objDict = {
  dataset1: [ { id: 1, count: 6 }, { id: 2, count: 7 }, { id: 3, count: 8 } ],
  dataset2: [ { id: 1, count: 5 }, { id: 2, count: 4 }, { id: 3, count: 3 } ]
}

I need to filter objects with specific id and create an array of count values: for id = 2 it would be countArray = [ 7, 4 ]. I suppose I should first use Object.values(objDict) but I don't know what to do afterwards.


Solution

  • Convert the object to an array with Object.values(), flatten to a single array, reduce and push the relevant count values to the accumulator (acc) array:

    const getCountById = (id, dict) => Object.values(objDict)
      .flat()
      .reduce((acc, { id: oid, count }) => {
        if(id === oid) acc.push(count)
      
        return acc
      }, [])
    
    
    const objDict = {
      dataset1: [ { id: 1, count: 6 }, { id: 2, count: 7 }, { id: 3, count: 8 } ],
      dataset2: [ { id: 1, count: 5 }, { id: 2, count: 4 }, { id: 3, count: 3 } ]
    }
    
    const result = getCountById(2, objDict)
    
    console.log(result)

    This is a bit of an abuse of reduce, the more idiomatic form would be to filter by the id, and then to map the objects to the count values:

    const getCountById = (id, dict) => Object.values(objDict)
      .flat()
      .filter(o => o.id === id)
      .map(o => o.count)
    
    
    const objDict = {
      dataset1: [ { id: 1, count: 6 }, { id: 2, count: 7 }, { id: 3, count: 8 } ],
      dataset2: [ { id: 1, count: 5 }, { id: 2, count: 4 }, { id: 3, count: 3 } ]
    }
    
    const result = getCountById(2, objDict)
    
    console.log(result)