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!

2
  • 2
    _ is underscore.js? Commented Mar 18, 2013 at 23:24
  • groupBy make. Select the maximum object per group (via map). map the desired value. Commented Mar 18, 2013 at 23:26

2 Answers 2

2

Check out Underscore's groupBy function. You should be able to use that and chain it with map

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

JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

1

you can do something 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"}
       ]

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.