Group objects in the mass



  • There's a set of objects. It's necessary. group by name and add the keys, If the name matches. I made a flag that filters repetition. I can't figure out how to sum it up.

    Dano:

    [{
        name: 'aaa',
        coin: 30
    },
    {
        name: 'bbb',
        coin: 32
    },
    {
        name: 'aaa',
        coin: 20
    },
    {
        name: 'aaa',
        coin: 50
    }]
    

    The result shall be:

    [{name: 'aaa', coin: 100}, {name: 'bbb', coin: 32}]
    

    My code is:

    const arr = [{
        name: 'aaa',
        price: 30
    },
    {
        name: 'bbb',
        price: 32
    },
    {
        name: 'aaa',
        price: 20
    },
    {
        name: 'aaa',
        price: 50
    }];
    const myFunction = (arr) => {
    let result = [];
    

    arr.forEach(object => {
    let flag = false;
    result.forEach((objectResult, index) => {
    if (object.name === objectResult.name){
    flag = true;
    }
    });
    if (!flag) result.push(object);
    });
    return result; };
    const test = myFunction(arr); console.log(test);



  • You can.

    We're going down the range with help. .reduce() with an initial battery as an empty object. We'll check on terations if our battery has a key equal to that. name♪ If not, we'll create a key with an initial value. { name: name, coin: 0 }♪ Verification and creation can be reduced to one step with assistance https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment ♪ Now we can add value. coin in this facility. At the end, we'll only be able to turn the battery into a set of objects with a bag with help. Object.values()

    const array = [{
        name: 'aaa',
        coin: 30
    },
    {
        name: 'bbb',
        coin: 32
    },
    {
        name: 'aaa',
        coin: 20
    },
    {
        name: 'aaa',
        coin: 50
    }];
    

    const array2 = Object.values(array.reduce(
    (acc, { name, coin }) => {
    acc[name] ??= { name, coin: 0 };
    acc[name].coin += coin;
    return acc;
    },
    {},
    ));

    console.log(array2);


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2