2

I have data that is an array of objects like this:

var cars = [ {"year": 2003, "make": "Toyota", "model": "Tercel"}
           , {"year": 2009, "make": "Toyota", "model": "Tercel"}
           , {"year": 1999, "make": "Honda", "model": "Civic"}
           , {"year": 2002, "make": "Honda", "model": "Civic"}
           , {"year": 2004, "make": "Honda", "model": "Civic"}
           , {"year": 2007, "make": "Honda", "model": "Accord"}
           ...
           ]

I want to pull out only the latest of each make and model, so that the selected array looks like:

var selectedCars = [ {"year": 2009, "make": "Toyota", "model": "Tercel"}
                   , {"year": 2004, "make": "Honda", "model": "Civic"}
                   , {"year": 2007, "make": "Honda", "model": "Accord"}
                   ]

I know that I can filter, e.g.:

var selectedCars = _.max(cars, function(d) { return d.year; })

but that returns a single object out of the entire array. I've also tried looping through a list of makes and models and selected just the max year, but I can't make that work.

Another option would be to nest the data via something like d3.nest() with make and model as keys, but then I'm not sure how to get back to my selectedCars goal.

Thanks!

4

2 回答 2

2

查看下划线的 groupBy函数。您应该能够使用它并将其与map

_.map(
    _.groupBy(cars, function(car) {
        return car.make + car.model;
    }),
    function(years, makeModel) {
        return _.max(years, function(year) {
            return year.year;
        });
    }
) 

JSFiddle

于 2013-03-18T23:31:08.277 回答
1

你可以做这样的事情

 var cars = [ {"year": 2003, "make": "Toyota", "model": "Tercel"}
       , {"year": 2009, "make": "Toyota", "model": "Tercel"}
       , {"year": 1999, "make": "Honda", "model": "Civic"}
       , {"year": 2002, "make": "Honda", "model": "Civic"}
       , {"year": 2004, "make": "Honda", "model": "Civic"}
       , {"year": 2007, "make": "Honda", "model": "Accord"}
       ]

var carGroup = _.groupBy(cars, 'make');
for (var property in carGroup) {
if (carGroup.hasOwnProperty(property)) {
    var selectedCar = _.max(carGroup[property], function(d) { return d.year; }) 
}
alert(JSON.stringify(selectedCar));
}

http://jsfiddle.net/btevfik/BEx5a/

于 2013-03-19T00:24:05.857 回答