从javascript中的对象数组中选择特定值

时间:2013-03-18 23:20:06

标签: javascript d3.js

我的数据是这样的对象数组:

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 selectedCars = [ {"year": 2009, "make": "Toyota", "model": "Tercel"}
                   , {"year": 2004, "make": "Honda", "model": "Civic"}
                   , {"year": 2007, "make": "Honda", "model": "Accord"}
                   ]

我知道我可以过滤,例如:

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

但是从整个数组中返回一个对象。我也试过循环制作品牌和型号列表并选择了最大年份,但我无法做到这一点。

另一种选择是通过类似d3.nest()的方式嵌套数据,使用make和model作为键,但后来我不确定如何回到我的selectedCars目标。

谢谢!

2 个答案:

答案 0 :(得分:2)

查看Underscore's groupBy功能。您应该能够使用它并将其与map

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

JSFiddle

答案 1 :(得分: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/