woodbine
woodbine

Reputation: 662

Javascript object sort and slice

I'm trying to sort and then slice a set of javascript objects. I'm successfully slicing the data, but the sort is returning a list of categories that is neither alphabetically sorted by category nor by value.

My CSV looks like this:

category,date_calc,value,YYYY,MM
string1,2011-08-01,46440.16,2011,8
string2,2013-03-01,68249.72,2013,3
string1,2014-01-01,4285,2014,1
string3,2012-03-01,47646.82,2012,3
...

This is my code:

d3.csv("data/ncc_category.csv", function(error, csv) {   
    var data = d3.nest()
    .key(function(d) { return d.category;})
    .rollup(function(d) { return d3.sum(d, function(g) {return g.value; }); }).entries(csv) 

    var sorted = data.sort(function (a, b) {
        return a.value - b.value; 
    }).reverse();

    var top10 = sorted.slice(0, 10); // slice
        console.log(top10);
});

EDIT: Screen grab for the first 4 objects in data.

Console output for data:

Screen grab for the first 4 objects in top10

Console output for top10

Upvotes: 0

Views: 2554

Answers (1)

woodbine
woodbine

Reputation: 662

Ok, so this is a salutary lesson in column naming, having named my column value, I didn't pick up on the fact that when d3 constructs a rolled up object array, it gives the primary column the name key and the summed column the name values. Once I changed the column name in the original csv I could see the problem, I also used the sorting code suggested here: Sort array of objects by string property value in JavaScript

d3.csv("data/ncc_category.csv", function(error, csv) {   
var data = d3.nest()
.key(function(d) { return d.category;})
.rollup(function(d) { return d3.sum(d, function(g) {return +g.total_spend; }); }).entries(csv)  

var sorted = data.sort(function (a, b) {
    if (a.values < b.values) {
        return 1;
}
    if (a.values > b.values) {
        return -1;
    }
    // a must be equal to b
    return 0;
});
console.dir(sorted);

var top10 = sorted.slice(0, 10); // slice the first 10
    console.dir(top10);
});

Upvotes: 1

Related Questions