且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算Javascript对象数组中的重复对象

更新时间:2022-04-12 09:09:02

你想要做的事情的根本很简单。您想要按某些属性对数据进行分组。让它看起来很复杂的是你想要在几个级别上做。

The root of what you want to do is simple. You want to group data by some property. What makes it seem complicated is that you want to do it at several levels.

首先你有3组数据寄售,运行,已售出。解决它为一个,你解决所有。

First you have 3 set of data "Consigned", "Run", "Sold". Solve it for one and you solve it for all.

首先你按车型分组汽车。在模型中,您可以按年份分组。同样,它的核心是你想要通过某些属性对数据进行分组。

First you have the cars grouped by model. Within the model you have the cars grouped by year. Again the core of it though is that you want to group data by some property.

你可以使用这样的函数来做到这一点:

You can use a function like this to do that:

var cars = [
            { year: 2007, model: "Ford F-150" },
            { year: 2011, model: "Toyota Camry" },
            { year: 2007, model: "Ford F-150" },
            { year: 2007, model: "Ford F-150" },
            { year: 2005, model: "Dodge RAM" }
        ];

function groupBy(propertyName, array) {
    var groupedElements = {};

    for(var i = 0; i < array.length; i++) {
        var element = array[i];
        var value = element[propertyName];

        var group = groupedElements[value];
        if(group == undefined) {
            group = [element];
            groupedElements[value] = group;
        } else {
            group.push(element);
        }
    }

    return groupedElements;
}

var result = groupBy("year", cars)

输出将是:

{
    "2005": [
        {
            "year": 2005,
            "model": "Dodge RAM"
        }
    ],
    "2007": [
        {
            "year": 2007,
            "model": "Ford F-150"
        },
        {
            "year": 2007,
            "model": "Ford F-150"
        },
        {
            "year": 2007,
            "model": "Ford F-150"
        }
    ],
    "2011": [
        {
            "year": 2011,
            "model": "Toyota Camry"
        }
    ]
}

你可以在这个JSFiddle中使用它: http://jsfiddle.net/luisperezphd/jCt2k/

You can play with it in this JSFiddle: http://jsfiddle.net/luisperezphd/jCt2k/

你可以完成你想要的做这个分组a每个级别。第一组逐年。然后逐个浏览每个生成组。您的计数将是值数组的长度

You can accomplish what you want to doing this grouping at each level. First group by year. Then go through each of the generate groups and group by year. Your count will be the length of the values array.