Skip to content Skip to sidebar Skip to footer

How To Group By The Array Values Dynamically In Javascript

hi all i am using javascript i have a set of array i need to group by the object code var data = [{BuildingID: '5', FloorId: '65', one: 12, two: 15,three: 12}, {Buildi

Solution 1:

You could use a dynamic approach by using a hash table and an array for the static keys of the object.

var data = [{ BuildingID: "5", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "5", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "6", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "6", FloorId: "65", one: 12, two: 15, three: 12 }],
    staticKeys = ['BuildingID', 'FloorId'] ,
    grouped = data.reduce(function (hash) {
        returnfunction (r, a) {
            var key = a[staticKeys[0]];
            if (!hash[key]) {
                hash[key] = {};
                staticKeys.forEach(function (k) {
                    hash[key][k] = a[k];
                });
                r.push(hash[key]);
            }
            Object.keys(a).forEach(function (k) {
                if (staticKeys.indexOf(k) === -1) {
                    hash[key][k] = (hash[key][k] || 0) + a[k];
                }
            });
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Solution 2:

here is a snippet code that work for me,

it assums you know the key attribute of the object

var arr = [ { id: 1, name: 'bob' }, { id: 1, name: 'bill' }, { id: 1, name: 'bill' } ]

var noDuplicate = [];
var unique = {};

$.each(arr, function(key, item) {

    if (! unique[item.id + "-" + item.name]) {
        noDuplicate.push(item);
        unique[item.id + "-" + item.name] = true;
    }
});

console.log(noDuplicate);

hope it helps ;)

regards.

Solution 3:

You can try this snippet, the "ouput" variable contains the result;

var data = [{ BuildingID: "5", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "5", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "6", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "6", FloorId: "65", one: 12, two: 15, three: 12 }]
var groupBy = function(input, key) {
   returninput.reduce(function(list, x) {
     list[x[key]] = x;
     return list;
   }, {});
};
var grouped = groupBy(data, 'BuildingID'), output=[];
for ( var key in grouped ) { output[output.length] = grouped[key]; }
console.log(output);

Post a Comment for "How To Group By The Array Values Dynamically In Javascript"