[Solved] JavaScript sorting and grouping items in array


Use objects for the grouping.

var categories = {};

function incrementBy(category, value) {
  if (!categories[category]) {
    categories[category] = 0;
  }
  categories[category] += value;
}

var datasetarr = [];
var pos;
for(var i = 0; i < arr.length; i++){
  console.log('unsorted ' + arr[i].type + ' ' + arr[i].quantity);
  incrementBy(arr[i].type, arr[i].quantity)
}

for(var category in categories){
  console.log('sorted ' + category + ' ' + categories[category]);
}

You can decompose the object if needed, through it into an array and sort it if required.

A little bit cleaner example, which might let you follow along a little bite better:

var arr = [{type: 'kitchen appliance', quantity: 2},
    {type: 'home entertainment', quantity: 2},
    {type: 'home entertainment', quantity: 3},
    {type: 'batteries & lightings', quantity: 2},
    {type: 'home entertainment', quantity: 2},
    {type: 'home appliance', quantity: 5},
    {type: 'kitchen appliance', quantity: 4},
    {type: 'kitchen appliance', quantity: 5},
    {type: 'kitchen appliance', quantity: 3},
    {type: 'kitchen appliance', quantity: 4},
    {type: 'kitchen appliance', quantity: 1},
    {type: 'home entertainment', quantity: 1},
    {type: 'home appliance', quantity: 5},
    {type: 'batteries & lightings', quantity: 2},
    {type: 'kitchen appliance', quantity: 2},
    {type: 'home appliance', quantity: 2}];


function group(array) {
    var categories = {};

    function incrementBy(category, value) {
        if (!categories[category]) {
            categories[category] = 0;
        }
        categories[category] += value;
    }

    array.forEach(function (value, index, arr) {
        incrementBy(value.type, value.quantity)
    });

    return categories;
}

function print(categories) {
    for (var category in categories) {
        console.log('%s: %s', category, categories[category]);
    }
}

print(group(arr));

Here a solution of of group hiding the grouping, which than can hold your own implementation:

function group(array) {
    var categories = {};

    function incrementBy(object) {
        var category = categories[object.type];
        if (!category) {
            category = categories[object.type] = {};
        }
        var subCategory = category[object.subType];
        if (!subCategory) {
            subCategory = category[object.subType] = {};
        }
        subCategory += object.value;
    }

    array.forEach(function (value, index, arr) {
        incrementBy(value, value.quantity)
    });

    return categories;
}

Depending on your use case, you could also flatten the structure:

function incrementBy(object) {
    var key = [object.type, object.subType].join("https://stackoverflow.com/");
    var category = categories[key];
    if (!category) {
        category = categories[key] = {};
    }
    subCategory += object.value;
}

But it might make sense to have various maps in place:

function groupings(array) {
    var groupings = {
      types: {},
      subTypes: {},
      paths: {}
    };

    function incrementBy(object) {
        var category = groupings['types'][object.type];
        if (!category) {
            category = groupings['types'][object.type] = {};
        }
        category += object.value;

        var subCategory = groupings['subTypes'][object.subType];
        if (!subCategory) {
            subCategory = groupings['subTypes'][object.subType] = {};
        }
        subCategory += object.value;


        var key = [object.type, object.subType].join("https://stackoverflow.com/");
        var path = groupings['paths'][key];
        if (!path) {
            path = groupings['paths'][key] = {};
        }
        path += object.value;
    }

    array.forEach(function (value, index, arr) {
        incrementBy(value, value.quantity)
    });

    return categories;
}

To avoid information loss on aggregations, you could simply create a more complex data structure:

function groupByAndSumBy(data, groupByProperty, sumByProperty) {
  var accumulator = {};

  data.forEach(function(object, index, array) {
      var localAcc = accumulator[groupByProperty]
            = accumulator[groupByProperty] || { items: [] };
      localAcc[sumByProperty]
            = (localAcc[sumByProperty] || 0) + object[sumByProperty];
      localAcc.items.push(object);
  });

  return accumulator;
}

function groupByMerchantNameAndSumByTotalSales(data) {
    return groupByAndSumBy(data, 'merchantName', 'totalSales');
}

This creates an aggregation which also contains the subset of the input array, which allows you a more detailed view on the data.

8

solved JavaScript sorting and grouping items in array