0

In these I need to add the array value in which pensionname are the same. Add all amount if pensionName value are the same and rechange the array into myoutput array.

My main array:

Object, Object, Object, Object, Object, Object, Object]
Object
    amount: 2000
    member: "1"
    name: "Peter Andrews"
    pensionName: "1A"
    rowId: "row_1"
Object
    amount: 2000
    member: "1"
    name: "Peter Andrews"
    pensionName: "1A"
    rowId: "row_2"
Object
    amount: 2000
    member: "1"
    name: "Peter Andrews"
    pensionName: "1A"
    rowId: "row_3"
Object
    amount: 2000
    member: "1"
    name: "Peter Andrews"
    pensionName: "1A"
    rowId: "row_4"
Object
    amount: 2000
    member: "2"
    name: "Peter Andrews"
    pensionName: "2A"
    rowId: "row_5"
Object
    amount: 2000
    member: "2"
    name: "Peter Andrews"
    pensionName: "2A"
    rowId: "row_6"
Object
    amount: 2000
    member: "2"
    name: "Peter Andrews"
    pensionName: "2A"
    rowId: "row_7"

I need the output as:

[Object, Object]
Object
    amount: 8000
    member: "1"
    name: "Peter Andrews"
    pensionName: "1A"
    rowId: "row_1"

Object
    amount: 6000
    member: "2"
    name: "Peter Andrews"
    pensionName: "2A"
    rowId: "row_2"

So I had done:

Enter code here
_.forEach(pension,function(item) {
    key = item['pensionName'];
    if (key != "0" && key !=""){
        if (typeof(groups[key]) == "undefined") {
            count++;
            str = "row_"+count;
            groups[key] = {'member' : item['member'],'name' : item['name'],'pensionName' : item['pensionName'],'amount' : item['amount'],'rowId' : str};
        }
        else {
            groups[key]['amount'] = parseFloat(groups[key]['amount']) + parseFloat(item['amount']);
        }
    }
});

It resulted in:

1A:Object, 2A: Object]
1A: Object
    amount :200
    member :1
    name : "hello"
    name2 : 1A
    id : "row_1"
2A: Object
    amount : 200
    member : 2
    name : "hello"
    name2 : "2A"
    id : "row_2"

But I can't push it into an array:

var pensionBalance = getPension();
            pensionBalance.map(function(v){
            arr.push(v);
            });

So how can I convert it into an array and push or any other method to add the array value?

9
  • An array is an object. What do you mean, you want to loose named properties? Commented Apr 1, 2016 at 19:06
  • array + "" should give you exactly what you want, [Object, object] Commented Apr 1, 2016 at 19:07
  • please add you source array/object in plain text/as literal Commented Apr 1, 2016 at 19:11
  • it seems to be overcomplicated ... strange structure Commented Apr 1, 2016 at 19:27
  • Any one willing to have a skype chat @RomanPerekhrest Commented Apr 1, 2016 at 19:30

4 Answers 4

1

Maybe this works for you, but I am not sure, what to do with rowId property. Take all or just the first?

Basically this solution works with the thisArg, here this from Array#forEach. this is used as a temporary object with references to array items of unique persons in grouped.

In the forEach loop, first it checks if the person is already in the grouped array and therfore in this. If not, a new object is generated and to a new property with the actual pensionName to this assigned and pushed to grouped.

Now we can access this object with the key of pensionName and add the amount and push rowId to the array for it.

temporary this object:

{
    "1A": {                       // generated in first loop
        "amount": 8000,
        "member": "1",
        "name": "Peter Andrews",
        "pensionName": "1A",
        "rowId": [
            "row_1",              // added in first
            "row_2",              // ... second
            "row_3",              // third
            "row_4"               // forth
        ]
    },
    "2A": {                       // generated in fifth loop
        "amount": 6000,
        "member": "2",
        "name": "Peter Andrews",
        "pensionName": "2A",
        "rowId": [
            "row_5",              // added in fifth
            "row_6",              // ... sixth
            "row_7"               // seventh
        ]
    }
}

var object = [{ amount: 2000, member: "1", name: "Peter Andrews", pensionName: "1A", rowId: "row_1" }, { amount: 2000, member: "1", name: "Peter Andrews", pensionName: "1A", rowId: "row_2" }, { amount: 2000, member: "3", name: "Peter Andrews", pensionName: "1A", rowId: "row_3" }, { amount: 2000, member: "1", name: "Peter Andrews", pensionName: "1A", rowId: "row_4" }, { amount: 2000, member: "2", name: "Peter Andrews", pensionName: "2A", rowId: "row_5" }, { amount: 2000, member: "2", name: "Peter Andrews", pensionName: "2A", rowId: "row_6" }, { amount: 2000, member: "2", name: "Peter Andrews", pensionName: "2A", rowId: "row_7" }],
    grouped = [];

object.forEach(function (a) {
    if (!this[a.pensionName]) {
        this[a.pensionName] = { amount: 0, member: a.member, name: a.name, pensionName: a.pensionName, rowId: [] };
        grouped.push(this[a.pensionName]);
    }
    this[a.pensionName].amount += a.amount;
    this[a.pensionName].rowId.push(a.rowId);
}, {});

document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');

Sign up to request clarification or add additional context in comments.

8 Comments

i had some modification in question. Please review
It works fine, but can you please explain this functionality.
Actually, this mentioned grouped data in that grouped data, key doesn't exit. then how it add the amount into that array. If this -> mention object, then how the amount had added and pushed into grouped array
yes ,But when data used to push into grouped array . grouped.push(this[a.pensionName]); used to push when key doesn't exit ?
Yeah, i got it, but while creating key the all data are pushed into grouped array. if already exit how the amount pushed int0 grouped array.
|
1

Consider the following approach using Array.forEach and Array.map functions:

var grouped = {}, grouped_arr;
// pension is your initial array
pension.forEach(function(v){
    var key = v["pensionName"];
    if (grouped[key]) {
        if (v["member"] === grouped[key]["member"] 
            && v["name"] === grouped[key]["name"]) {
            grouped[key]["amount"] += v["amount"];
        }
    } else {
        grouped[key] = v;
    }
});

grouped_arr = Object.keys(grouped).map(function(k, i){
    var obj = grouped[k];
    obj["rowId"] = obj["rowId"].substring(0, obj["rowId"].indexOf("_") + 1) + (i+1);
    return obj;
});

document.write('<pre>' + JSON.stringify(grouped_arr, 0, 4) + '</pre>');

The output:

[
    {
        "amount": 8000,
        "member": "1",
        "name": "Peter Andrews",
        "pensionName": "1A",
        "rowId": "row_1"
    },
    {
        "amount": 6000,
        "member": "2",
        "name": "Peter Andrews",
        "pensionName": "2A",
        "rowId": "row_2"
    }
]

Comments

1

Alternative solution:

var output = [];

pension
  .forEach(function (v, i, arr) {

    var exists = output
      .reduce(function (a, c) {
        return c.pensionName === v.pensionName ? true : a;
      }, false);

    if (exists) return;

    var obj = arr
      .filter(function (p) {
        return p.pensionName === v.pensionName;
      })
      .reduce(function (a, c) {
        a.amount = a.amount + c.amount;
        return a
      });

    output.push(obj);
  });

output.map(function (v, i) {
  v.rowId = 'row_' + (i + 1);

  return v;
});

Comments

0
var pension = [{ amount: 2000, member: "1", name: "Peter Andrews", pensionName: "1A", rowId: "row_1" }, { amount: 2000, member: "1", name: "Peter Andrews", pensionName: "1A", rowId: "row_2" }, { amount: 2000, member: "3", name: "Peter Andrews", pensionName: "1A", rowId: "row_3" }, { amount: 2000, member: "1", name: "Peter Andrews", pensionName: "1A", rowId: "row_4" }, { amount: 2000, member: "2", name: "Peter Andrews", pensionName: "2A", rowId: "row_5" }, { amount: 2000, member: "2", name: "Peter Andrews", pensionName: "2A", rowId: "row_6" }, { amount: 2000, member: "2", name: "Peter Andrews", pensionName: "2A", rowId: "row_7" }],
grouped = [];
var pensionData = new Array();
var count = 0;
var str;

pension.forEach(function (a) {
  if (!this[a.pensionName]) { 
    count++;
    str = "row_"+count;
    this[a.pensionName] = { amount: 0, member: a.member, name: a.name, pensionName: a.pensionName, rowId: str };
     pensionData.push(this[a.pensionName]);
  }
 this[a.pensionName].amount += a.amount;
}, {});

The output:

[
 {
    "amount": 8000,
    "member": "1",
    "name": "Peter Andrews",
    "pensionName": "1A",
    "rowId": "row_1"
 },
 {
    "amount": 6000,
    "member": "2",
    "name": "Peter Andrews",
    "pensionName": "2A",
    "rowId": "row_2"
 }
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.