joshua
joshua

Reputation: 2371

Merge values of array by duplicate keys

Trying to merge duplicate keys of json array and build respective values in csv format.

A=[{a:1,b:2},{a:1,b:1},{a:1,b:6},{a:2,b:5},{a:2,b:3}]

Trying to convert in

A=[{a:'1',b:'2,1,6'},{a:2,b:'5,3'}]

code Which i tried

var existingIDs = [];
        A= $.grep(A, function (v) {
            if ($.inArray(v.a, existingIDs) !== -1) {
                return v.b+= ',';
            }
            else {
                existingIDs.push(v.a);
                return true;
            }
        });

the output is returns like

A=[{a:1,b:2},{a:1,b:'1,'},{a:1,b:'6,'},{a:2,b:5},{a:2,b:'3,'}]

Upvotes: 4

Views: 1800

Answers (1)

adeneo
adeneo

Reputation: 318182

Create a temporary object with 1, 2 etc from a as keys and keep adding on the b values, then iterate over that object creating the new array :

var A = [{a:1,b:2},{a:1,b:1},{a:1,b:6},{a:2,b:5},{a:2,b:3}];
var temp = {};

for (var i=0; i<A.length; i++) {
    temp[A[i].a] =
        temp[A[i].a] === undefined ?
            A[i].b :
            temp[A[i].a] + ',' + A[i].b;
}

A = [];

for (var key in temp) {
    A.push({a: key, b:temp[key]})
}

FIDDLE

Upvotes: 2

Related Questions