How do I get the following output from this array of objects?











up vote
0
down vote

favorite












This is the original array of objects:



const input = [

{firstProperty: 'something',
money: 3,
user: 'john-smith'},
{firstProperty: 'somethingDiff',
money: 7,
user: 'john-smith'},
{firstProperty: 'somElse',
money: 14,
user: 'jane-doe'},
{firstProperty: 'someOtherThing',
money: 2,
user: 'jane-doe'}]


And I would need to output the following:



const output = [
{user: 'john-smith',
totalMoney: 10},
{user: 'jane-doe',
totalMoney: 16}]


I have already achieved this result by using a bunch of for loops but I was looking for an elegant solution that uses only ES6 methods such as map, filter, reduce, etc.










share|improve this question




















  • 2




    Your input makes little sense.
    – Jonas Wilms
    Nov 10 at 12:00










  • This would make more sense if you change your input a bit (if possible of course). It would make more sense if the input was like this: [ {firstProperty: "something, money: 3, user:"john smith""}, {firstProperty: "somethingelse", money: 4, user:"john smith""} ]. Copy and compare and you'll see what we mean
    – Mr.Turtle
    Nov 10 at 12:05












  • Looks like you edited Data Structure from original one. Updated my answer as well.
    – Nitish Narang
    Nov 10 at 13:59















up vote
0
down vote

favorite












This is the original array of objects:



const input = [

{firstProperty: 'something',
money: 3,
user: 'john-smith'},
{firstProperty: 'somethingDiff',
money: 7,
user: 'john-smith'},
{firstProperty: 'somElse',
money: 14,
user: 'jane-doe'},
{firstProperty: 'someOtherThing',
money: 2,
user: 'jane-doe'}]


And I would need to output the following:



const output = [
{user: 'john-smith',
totalMoney: 10},
{user: 'jane-doe',
totalMoney: 16}]


I have already achieved this result by using a bunch of for loops but I was looking for an elegant solution that uses only ES6 methods such as map, filter, reduce, etc.










share|improve this question




















  • 2




    Your input makes little sense.
    – Jonas Wilms
    Nov 10 at 12:00










  • This would make more sense if you change your input a bit (if possible of course). It would make more sense if the input was like this: [ {firstProperty: "something, money: 3, user:"john smith""}, {firstProperty: "somethingelse", money: 4, user:"john smith""} ]. Copy and compare and you'll see what we mean
    – Mr.Turtle
    Nov 10 at 12:05












  • Looks like you edited Data Structure from original one. Updated my answer as well.
    – Nitish Narang
    Nov 10 at 13:59













up vote
0
down vote

favorite









up vote
0
down vote

favorite











This is the original array of objects:



const input = [

{firstProperty: 'something',
money: 3,
user: 'john-smith'},
{firstProperty: 'somethingDiff',
money: 7,
user: 'john-smith'},
{firstProperty: 'somElse',
money: 14,
user: 'jane-doe'},
{firstProperty: 'someOtherThing',
money: 2,
user: 'jane-doe'}]


And I would need to output the following:



const output = [
{user: 'john-smith',
totalMoney: 10},
{user: 'jane-doe',
totalMoney: 16}]


I have already achieved this result by using a bunch of for loops but I was looking for an elegant solution that uses only ES6 methods such as map, filter, reduce, etc.










share|improve this question















This is the original array of objects:



const input = [

{firstProperty: 'something',
money: 3,
user: 'john-smith'},
{firstProperty: 'somethingDiff',
money: 7,
user: 'john-smith'},
{firstProperty: 'somElse',
money: 14,
user: 'jane-doe'},
{firstProperty: 'someOtherThing',
money: 2,
user: 'jane-doe'}]


And I would need to output the following:



const output = [
{user: 'john-smith',
totalMoney: 10},
{user: 'jane-doe',
totalMoney: 16}]


I have already achieved this result by using a bunch of for loops but I was looking for an elegant solution that uses only ES6 methods such as map, filter, reduce, etc.







javascript arrays object ecmascript-6






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 at 13:17

























asked Nov 10 at 11:56









nicokruk

244




244








  • 2




    Your input makes little sense.
    – Jonas Wilms
    Nov 10 at 12:00










  • This would make more sense if you change your input a bit (if possible of course). It would make more sense if the input was like this: [ {firstProperty: "something, money: 3, user:"john smith""}, {firstProperty: "somethingelse", money: 4, user:"john smith""} ]. Copy and compare and you'll see what we mean
    – Mr.Turtle
    Nov 10 at 12:05












  • Looks like you edited Data Structure from original one. Updated my answer as well.
    – Nitish Narang
    Nov 10 at 13:59














  • 2




    Your input makes little sense.
    – Jonas Wilms
    Nov 10 at 12:00










  • This would make more sense if you change your input a bit (if possible of course). It would make more sense if the input was like this: [ {firstProperty: "something, money: 3, user:"john smith""}, {firstProperty: "somethingelse", money: 4, user:"john smith""} ]. Copy and compare and you'll see what we mean
    – Mr.Turtle
    Nov 10 at 12:05












  • Looks like you edited Data Structure from original one. Updated my answer as well.
    – Nitish Narang
    Nov 10 at 13:59








2




2




Your input makes little sense.
– Jonas Wilms
Nov 10 at 12:00




Your input makes little sense.
– Jonas Wilms
Nov 10 at 12:00












This would make more sense if you change your input a bit (if possible of course). It would make more sense if the input was like this: [ {firstProperty: "something, money: 3, user:"john smith""}, {firstProperty: "somethingelse", money: 4, user:"john smith""} ]. Copy and compare and you'll see what we mean
– Mr.Turtle
Nov 10 at 12:05






This would make more sense if you change your input a bit (if possible of course). It would make more sense if the input was like this: [ {firstProperty: "something, money: 3, user:"john smith""}, {firstProperty: "somethingelse", money: 4, user:"john smith""} ]. Copy and compare and you'll see what we mean
– Mr.Turtle
Nov 10 at 12:05














Looks like you edited Data Structure from original one. Updated my answer as well.
– Nitish Narang
Nov 10 at 13:59




Looks like you edited Data Structure from original one. Updated my answer as well.
– Nitish Narang
Nov 10 at 13:59












2 Answers
2






active

oldest

votes

















up vote
2
down vote



accepted










With the updated code it makes it even easier to get your result, my approach would still be to first aggregate and then map.



I updated the code per changes to your original post.






const input = [
{firstProperty: 'something',
money: 3,
user: 'john-smith'},
{firstProperty: 'somethingDiff',
money: 7,
user: 'john-smith'},
{firstProperty: 'somElse',
money: 14,
user: 'jane-doe'},
{firstProperty: 'someOtherThing',
money: 2,
user: 'jane-doe'}
];

function sumByUser( input ) {
// first aggregate the money per user
const moneyByUser = input.reduce( (current, { user, money }) => {
current[user] = (current[user] || 0) + money;
return current;
}, {} );

// then create an array by using the keys for user names
return Object
.keys( moneyByUser )
.map( user => ({ user, money: moneyByUser[user] }) );
}

console.log( sumByUser( input ) );








share|improve this answer























  • sorry, my input was wrong after all. I pasted the indexers without intention.
    – nicokruk
    Nov 10 at 13:06












  • @nicokruk well, you only need to remove the object.values statement to make it work, so it would be easy yo adapt my current code to your needs
    – Icepickle
    Nov 10 at 13:07












  • @nicokruk I updated the code, but as mentioned before this shouldn't have been a big deal as the principal still stands
    – Icepickle
    Nov 10 at 13:15


















up vote
0
down vote













You can use below approach of "Array.reduce" and "Array.from" as well






var input = [{firstProperty: 'something', money: 3, user: 'john-smith'}, {firstProperty: 'somethingDiff', money: 7, user: 'john-smith'}, {firstProperty: 'somElse', money: 14, user: 'jane-doe'},{firstProperty: 'someOtherThing', money: 2, user: 'jane-doe'}]

var result = Array.from(input.reduce((m, { user, money }) =>
m.set(user, { user, totalMoney: (m.get(user) && m.get(user).totalMoney || 0) + money })
, new Map)
, ([ _, d ]) => d)



console.log(result)








share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53238693%2fhow-do-i-get-the-following-output-from-this-array-of-objects%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    2
    down vote



    accepted










    With the updated code it makes it even easier to get your result, my approach would still be to first aggregate and then map.



    I updated the code per changes to your original post.






    const input = [
    {firstProperty: 'something',
    money: 3,
    user: 'john-smith'},
    {firstProperty: 'somethingDiff',
    money: 7,
    user: 'john-smith'},
    {firstProperty: 'somElse',
    money: 14,
    user: 'jane-doe'},
    {firstProperty: 'someOtherThing',
    money: 2,
    user: 'jane-doe'}
    ];

    function sumByUser( input ) {
    // first aggregate the money per user
    const moneyByUser = input.reduce( (current, { user, money }) => {
    current[user] = (current[user] || 0) + money;
    return current;
    }, {} );

    // then create an array by using the keys for user names
    return Object
    .keys( moneyByUser )
    .map( user => ({ user, money: moneyByUser[user] }) );
    }

    console.log( sumByUser( input ) );








    share|improve this answer























    • sorry, my input was wrong after all. I pasted the indexers without intention.
      – nicokruk
      Nov 10 at 13:06












    • @nicokruk well, you only need to remove the object.values statement to make it work, so it would be easy yo adapt my current code to your needs
      – Icepickle
      Nov 10 at 13:07












    • @nicokruk I updated the code, but as mentioned before this shouldn't have been a big deal as the principal still stands
      – Icepickle
      Nov 10 at 13:15















    up vote
    2
    down vote



    accepted










    With the updated code it makes it even easier to get your result, my approach would still be to first aggregate and then map.



    I updated the code per changes to your original post.






    const input = [
    {firstProperty: 'something',
    money: 3,
    user: 'john-smith'},
    {firstProperty: 'somethingDiff',
    money: 7,
    user: 'john-smith'},
    {firstProperty: 'somElse',
    money: 14,
    user: 'jane-doe'},
    {firstProperty: 'someOtherThing',
    money: 2,
    user: 'jane-doe'}
    ];

    function sumByUser( input ) {
    // first aggregate the money per user
    const moneyByUser = input.reduce( (current, { user, money }) => {
    current[user] = (current[user] || 0) + money;
    return current;
    }, {} );

    // then create an array by using the keys for user names
    return Object
    .keys( moneyByUser )
    .map( user => ({ user, money: moneyByUser[user] }) );
    }

    console.log( sumByUser( input ) );








    share|improve this answer























    • sorry, my input was wrong after all. I pasted the indexers without intention.
      – nicokruk
      Nov 10 at 13:06












    • @nicokruk well, you only need to remove the object.values statement to make it work, so it would be easy yo adapt my current code to your needs
      – Icepickle
      Nov 10 at 13:07












    • @nicokruk I updated the code, but as mentioned before this shouldn't have been a big deal as the principal still stands
      – Icepickle
      Nov 10 at 13:15













    up vote
    2
    down vote



    accepted







    up vote
    2
    down vote



    accepted






    With the updated code it makes it even easier to get your result, my approach would still be to first aggregate and then map.



    I updated the code per changes to your original post.






    const input = [
    {firstProperty: 'something',
    money: 3,
    user: 'john-smith'},
    {firstProperty: 'somethingDiff',
    money: 7,
    user: 'john-smith'},
    {firstProperty: 'somElse',
    money: 14,
    user: 'jane-doe'},
    {firstProperty: 'someOtherThing',
    money: 2,
    user: 'jane-doe'}
    ];

    function sumByUser( input ) {
    // first aggregate the money per user
    const moneyByUser = input.reduce( (current, { user, money }) => {
    current[user] = (current[user] || 0) + money;
    return current;
    }, {} );

    // then create an array by using the keys for user names
    return Object
    .keys( moneyByUser )
    .map( user => ({ user, money: moneyByUser[user] }) );
    }

    console.log( sumByUser( input ) );








    share|improve this answer














    With the updated code it makes it even easier to get your result, my approach would still be to first aggregate and then map.



    I updated the code per changes to your original post.






    const input = [
    {firstProperty: 'something',
    money: 3,
    user: 'john-smith'},
    {firstProperty: 'somethingDiff',
    money: 7,
    user: 'john-smith'},
    {firstProperty: 'somElse',
    money: 14,
    user: 'jane-doe'},
    {firstProperty: 'someOtherThing',
    money: 2,
    user: 'jane-doe'}
    ];

    function sumByUser( input ) {
    // first aggregate the money per user
    const moneyByUser = input.reduce( (current, { user, money }) => {
    current[user] = (current[user] || 0) + money;
    return current;
    }, {} );

    // then create an array by using the keys for user names
    return Object
    .keys( moneyByUser )
    .map( user => ({ user, money: moneyByUser[user] }) );
    }

    console.log( sumByUser( input ) );








    const input = [
    {firstProperty: 'something',
    money: 3,
    user: 'john-smith'},
    {firstProperty: 'somethingDiff',
    money: 7,
    user: 'john-smith'},
    {firstProperty: 'somElse',
    money: 14,
    user: 'jane-doe'},
    {firstProperty: 'someOtherThing',
    money: 2,
    user: 'jane-doe'}
    ];

    function sumByUser( input ) {
    // first aggregate the money per user
    const moneyByUser = input.reduce( (current, { user, money }) => {
    current[user] = (current[user] || 0) + money;
    return current;
    }, {} );

    // then create an array by using the keys for user names
    return Object
    .keys( moneyByUser )
    .map( user => ({ user, money: moneyByUser[user] }) );
    }

    console.log( sumByUser( input ) );





    const input = [
    {firstProperty: 'something',
    money: 3,
    user: 'john-smith'},
    {firstProperty: 'somethingDiff',
    money: 7,
    user: 'john-smith'},
    {firstProperty: 'somElse',
    money: 14,
    user: 'jane-doe'},
    {firstProperty: 'someOtherThing',
    money: 2,
    user: 'jane-doe'}
    ];

    function sumByUser( input ) {
    // first aggregate the money per user
    const moneyByUser = input.reduce( (current, { user, money }) => {
    current[user] = (current[user] || 0) + money;
    return current;
    }, {} );

    // then create an array by using the keys for user names
    return Object
    .keys( moneyByUser )
    .map( user => ({ user, money: moneyByUser[user] }) );
    }

    console.log( sumByUser( input ) );






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 10 at 13:14

























    answered Nov 10 at 12:06









    Icepickle

    8,24332034




    8,24332034












    • sorry, my input was wrong after all. I pasted the indexers without intention.
      – nicokruk
      Nov 10 at 13:06












    • @nicokruk well, you only need to remove the object.values statement to make it work, so it would be easy yo adapt my current code to your needs
      – Icepickle
      Nov 10 at 13:07












    • @nicokruk I updated the code, but as mentioned before this shouldn't have been a big deal as the principal still stands
      – Icepickle
      Nov 10 at 13:15


















    • sorry, my input was wrong after all. I pasted the indexers without intention.
      – nicokruk
      Nov 10 at 13:06












    • @nicokruk well, you only need to remove the object.values statement to make it work, so it would be easy yo adapt my current code to your needs
      – Icepickle
      Nov 10 at 13:07












    • @nicokruk I updated the code, but as mentioned before this shouldn't have been a big deal as the principal still stands
      – Icepickle
      Nov 10 at 13:15
















    sorry, my input was wrong after all. I pasted the indexers without intention.
    – nicokruk
    Nov 10 at 13:06






    sorry, my input was wrong after all. I pasted the indexers without intention.
    – nicokruk
    Nov 10 at 13:06














    @nicokruk well, you only need to remove the object.values statement to make it work, so it would be easy yo adapt my current code to your needs
    – Icepickle
    Nov 10 at 13:07






    @nicokruk well, you only need to remove the object.values statement to make it work, so it would be easy yo adapt my current code to your needs
    – Icepickle
    Nov 10 at 13:07














    @nicokruk I updated the code, but as mentioned before this shouldn't have been a big deal as the principal still stands
    – Icepickle
    Nov 10 at 13:15




    @nicokruk I updated the code, but as mentioned before this shouldn't have been a big deal as the principal still stands
    – Icepickle
    Nov 10 at 13:15












    up vote
    0
    down vote













    You can use below approach of "Array.reduce" and "Array.from" as well






    var input = [{firstProperty: 'something', money: 3, user: 'john-smith'}, {firstProperty: 'somethingDiff', money: 7, user: 'john-smith'}, {firstProperty: 'somElse', money: 14, user: 'jane-doe'},{firstProperty: 'someOtherThing', money: 2, user: 'jane-doe'}]

    var result = Array.from(input.reduce((m, { user, money }) =>
    m.set(user, { user, totalMoney: (m.get(user) && m.get(user).totalMoney || 0) + money })
    , new Map)
    , ([ _, d ]) => d)



    console.log(result)








    share|improve this answer



























      up vote
      0
      down vote













      You can use below approach of "Array.reduce" and "Array.from" as well






      var input = [{firstProperty: 'something', money: 3, user: 'john-smith'}, {firstProperty: 'somethingDiff', money: 7, user: 'john-smith'}, {firstProperty: 'somElse', money: 14, user: 'jane-doe'},{firstProperty: 'someOtherThing', money: 2, user: 'jane-doe'}]

      var result = Array.from(input.reduce((m, { user, money }) =>
      m.set(user, { user, totalMoney: (m.get(user) && m.get(user).totalMoney || 0) + money })
      , new Map)
      , ([ _, d ]) => d)



      console.log(result)








      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        You can use below approach of "Array.reduce" and "Array.from" as well






        var input = [{firstProperty: 'something', money: 3, user: 'john-smith'}, {firstProperty: 'somethingDiff', money: 7, user: 'john-smith'}, {firstProperty: 'somElse', money: 14, user: 'jane-doe'},{firstProperty: 'someOtherThing', money: 2, user: 'jane-doe'}]

        var result = Array.from(input.reduce((m, { user, money }) =>
        m.set(user, { user, totalMoney: (m.get(user) && m.get(user).totalMoney || 0) + money })
        , new Map)
        , ([ _, d ]) => d)



        console.log(result)








        share|improve this answer














        You can use below approach of "Array.reduce" and "Array.from" as well






        var input = [{firstProperty: 'something', money: 3, user: 'john-smith'}, {firstProperty: 'somethingDiff', money: 7, user: 'john-smith'}, {firstProperty: 'somElse', money: 14, user: 'jane-doe'},{firstProperty: 'someOtherThing', money: 2, user: 'jane-doe'}]

        var result = Array.from(input.reduce((m, { user, money }) =>
        m.set(user, { user, totalMoney: (m.get(user) && m.get(user).totalMoney || 0) + money })
        , new Map)
        , ([ _, d ]) => d)



        console.log(result)








        var input = [{firstProperty: 'something', money: 3, user: 'john-smith'}, {firstProperty: 'somethingDiff', money: 7, user: 'john-smith'}, {firstProperty: 'somElse', money: 14, user: 'jane-doe'},{firstProperty: 'someOtherThing', money: 2, user: 'jane-doe'}]

        var result = Array.from(input.reduce((m, { user, money }) =>
        m.set(user, { user, totalMoney: (m.get(user) && m.get(user).totalMoney || 0) + money })
        , new Map)
        , ([ _, d ]) => d)



        console.log(result)





        var input = [{firstProperty: 'something', money: 3, user: 'john-smith'}, {firstProperty: 'somethingDiff', money: 7, user: 'john-smith'}, {firstProperty: 'somElse', money: 14, user: 'jane-doe'},{firstProperty: 'someOtherThing', money: 2, user: 'jane-doe'}]

        var result = Array.from(input.reduce((m, { user, money }) =>
        m.set(user, { user, totalMoney: (m.get(user) && m.get(user).totalMoney || 0) + money })
        , new Map)
        , ([ _, d ]) => d)



        console.log(result)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 10 at 13:58

























        answered Nov 10 at 12:38









        Nitish Narang

        1,27269




        1,27269






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53238693%2fhow-do-i-get-the-following-output-from-this-array-of-objects%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            Popular posts from this blog

            Coverage of Google Street View

            Full-time equivalent

            Surfing