简体   繁体   中英

How to fill the array of sets by key and sum the values Lodash.js

I am using JS and LoDash library.

Data that I receive from the server looks like this:

const statsToSort = [
{name: "critA", value: 11111},
{name: "critA", value: 11},
{name: "critA", value: 221},
{name: "critA", value: 54},
{name: "critB", value: 1222},
{name: "critC", value: 231},
{name: "critD", value: 323},
{name: "critC", value: 0},
]

I Need to rearrange it, summ the values for the same keys and reOrganise it. For this I created the following array:

let finalStats = [{ "critA": 0 }, { "critB": 0 }, { "critC": 0 }, { "CritD": 0 }];

I am trying to use the Lodash library to fill the finalStats jumping of the name and summing the values.

The function I have so far is like this:

function mergeNames(arr) {
    return _.chain(arr).groupBy('name').mapValues(function (v) {
        return _.sum(v);
    })

The expected result is supposed to be like this:

/**
statsToSort:[
{name: "critA", value:11397},
{name: "critB", value:1222},
{name: "critC", value:231},
{name: "critD", value:323}, 
*/

So far my function that I have shown does...Nothing. Like, at all. It does not even sort the array by keys.

Question: Can you help me

  • modify the function to get the result I mentioned
  • maybe add another layer to the function so that it would do the populating of the finalStats array considering that the names might not be alphabetically arranged and statsToSort might not contain one or few names that are to be populated in the finalStats.

Thanks in advance

You could take a map and get the summed values.

 const statsToSort = [{ name: "critA", value: 11111 }, { name: "critA", value: 11 }, { name: "critA", value: 221 }, { name: "critA", value: 54 }, { name: "critB", value: 1222 }, { name: "critC", value: 231 }, { name: "critD", value: 323 }, { name: "critC", value: 0 }], result = Array.from( statsToSort.reduce((m, { name, value }) => m.set(name, (m.get(name) || 0) + value), new Map), ([name, value]) => ({ name, value }) ).sort((a, b) => a.name.localeCompare(b.name)); console.log(result);

This appears to do what you're after:

 const statsToSort = [ {name: "critA", value: 11111}, {name: "critA", value: 11}, {name: "critA", value: 221}, {name: "critA", value: 54}, {name: "critB", value: 1222}, {name: "critC", value: 231}, {name: "critD", value: 323}, {name: "critC", value: 0}, ] let mergeNames = arr => _(arr).groupBy('name').mapValues(vals => ({ name: vals[0].name, value: _.sumBy(vals, 'value') })).value() let finalStats = mergeNames(statsToSort) console.log(finalStats)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM