JSFiddle - React, Tailwind, and code Playground

by chridam

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js"></script>
<div id="results"></div>

CSS

body {font-family: "Courier New";}

JavaScript

// Sample data
arr = [{ name: 'happ', qty: 1, price: 50 },
       { name: 'happ', qty: 1, price: 50 },
       { name: 'happ', qty: 1, price: 50 },
       { name: 'happ', qty: 2, price: 10 },
       { name: 'app', qty: 1, price: 50 },
       { name: 'app', qty: 1, price: 50 },
       { name: 'app', qty: 1, price: 50 },
       { name: 'app', qty: 2, price: 10 }];

var groupedObjects = arr.reduce(function(res, obj) {
    if (!((obj.name + obj.price) in res))
        res.__array.push(res[obj.name + obj.price] = obj);
    else {
        res[obj.name + obj.price].qty += obj.qty;        
    }
    return res;
}, {__array:[]}).__array
                .sort(function(a,b) { return b.qty - a.qty; });



// print results for testing
_.each(groupedObjects,function(obj){
    var output = '';
    _.each(obj,function(val,key){
        output += key+': '+val+'<br>';         
    });
    output += '<br>';
    $('#results').append(output);
});