Search code examples
javascriptjsonunderscore.jslodash

Javascript count distinct value and sum lists in json array


For example, in the following json array each element has a name and a variable list of items in tracks.items

[
    {
    "name": "whatever",
    "tracks": {
        "items": 
        [
            {
             "item 1" : "some item" 
            },
            ...
        ]
        }
    },
    {...}
    ...
]

In javascript, I need to find the number of distinct name's, as well as the sum of the length (size) of all tracks.items found in the entire array.
How do I use underscore or lodash to do that?. I've tried _.countBy() but that only returns individual counts

EDIT
thanks guys
(alternate solution)
const uniqueNames = new Set(array.map(item => item.name)).size const totalItems = array.reduce((sum, item) => sum + item.tracks.items.length, 0)


Solution

  • As Stucco noted in his answer you can get the number of unique names, by checking the length of the result of _.uniqBy() by name.

    You can get the total amount of track items using _.sumBy().

    var arr = [{"name":"whatever","tracks":{"items":[{"item 1":"some item"},{"item 2":"some item"},{"item 3":"some item"}]}},{"name":"whatever","tracks":{"items":[{"item 4":"some item"},{"item 5":"some item"},{"item 6":"some item"},{"item 7":"some item"}]}},{"name":"whatever2","tracks":{"items":[{"item 8":"some item"},{"item 9":"some item"},{"item 10":"some item"},{"item 11":"some item"}]}}];
    
    var uniqueNamesCount = _.uniqBy(arr, 'name').length;
    var totalTracksItemsCount = _.sumBy(arr, 'tracks.items.length');
    
    console.log('uniqueNamesCount', uniqueNamesCount); // 2
    console.log('totalTracksItemsCount', totalTracksItemsCount); // 11
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>