1

I have a collection (Products) and I use _.countBy like this :

var totalByBrand = _.countBy(result, "Brand");

and I have this result :

{
    'Brand 1 ' : 5,
    'Brand 2 ' : 45,
    'Brand 3 ' : 2,
    ...
    'Brand 99 ' : 25
}

I try to sort this result to obtain that :

{
    'Brand 3 ' : 2,
    'Brand 1 ' : 5,
    'Brand 99 ' : 25,
    ...
    'Brand 2 ' : 45
}

Is it possible with _.sortBy() ?

nikoshr
  • 31,776
  • 30
  • 87
  • 102

1 Answers1

4

Properties order cannot be guaranteed in JavaScript Does JavaScript Guarantee Object Property Order? and that means you can't sort them.

You would have to use a different structure, maybe a list of objects like {brand: ..., count: ...} and sort on on count. For example

var totalByBrand = _.countBy(products, 'Brand');

var sorted = _.chain(totalByBrand).
    map(function(cnt, brand) {
        return {
            brand: brand,
            count: cnt
        }
    })
    .sortBy('count')
    .value();

And a demo

var products = [
    {Brand: "Brand 1", id: 1},
    {Brand: "Brand 1", id: 2},
    {Brand: "Brand 2", id: 3},
    {Brand: "Brand 3", id: 4},
    {Brand: "Brand 3", id: 5},
    {Brand: "Brand 1", id: 6},
];

var totalByBrand = _.countBy(products, 'Brand');
    
var sorted = _.chain(totalByBrand).
    map(function(cnt, brand) {
        return {
            brand: brand,
            count: cnt
        }
    }).sortBy('count')
    .value();
    
console.dir(
    sorted
);
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.0/underscore-min.js"></script>
nikoshr
  • 31,776
  • 30
  • 87
  • 102