计算Javascript数组的出现次数

时间:2015-07-27 20:50:02

标签: javascript arrays

我试图计算一个对象数组中的出现次数,并返回另一个出现的数组。



var data = [
    {
        absCost: 0,
        absEndDate: "2014-04-24T00:00:00+01:00",
        absId: "#",
        absMins: 3152,
        absStartDate: "2015-04-08T00:00:00+01:00",
        absType: "Annual Leave",
        absenceReason: "",
        authorise: "Undecided",
        department: "St Catherine's Ward",
        empName: "Alison Lane",
        empNo: " 06547",
        empid: 575,
        status: "",
        year: 2014
    },{
        absCost: 0,
        absEndDate: "2015-04-24T00:00:00+01:00",
        absId: "#",
        absMins: 3152,
        absStartDate: "2015-04-08T00:00:00+01:00",
        absType: "Annual Leave",
        absenceReason: "",
        authorise: "Undecided",
        department: "St Catherine's Ward",
        empName: "Alison Lane",
        empNo: " 06547",
        empid: 575,
        status: "",
        year: 2015
    },
    {
        absCost: 0,
        absEndDate: "2015-04-24T00:00:00+01:00",
        absId: "#",
        absMins: 3152,
        absStartDate: "2015-04-08T00:00:00+01:00",
        absType: "Annual Leave",
        absenceReason: "",
        authorise: "Undecided",
        department: "St Catherine's Ward",
        empName: "Alison Lane",
        empNo: " 06547",
        empid: 575,
        status: "",
        year: 2015
    }];


var finalArray = [];


for (var idx=0; i>data.length; i++){
  finalArray.push({
    year: data[i].year,
    frequency: //number of occurrences of the Year
  });
}


//Hi Would like to get this result:

/*
finalArray=[{
   year: 2014,
   frequency: 1
},{
   year: 2015,
   frequency: 2
}];      */                

         




3 个答案:

答案 0 :(得分:1)

您可以将关联数组与Output/**/*.xml结合使用来实现该目标:

filter()

jsfiddle

答案 1 :(得分:1)

你可以尝试一下,无论如何这是非常简单的方法:

var years = [];

for (var i=0; i<data.length; i++){
  years.push(data[i].year);
}
years.sort();

var finalArray = [];
var occurence = 1;
for (var i=0; i<=years.length-1; i++){
    console.log(years[i])
    if (years[i] === years[i+1]) {
        occurence += 1;
    } else {
        finalArray.push({year: years[i], frequency: occurence});
        occurence = 1;
    }
}

DEMO

答案 2 :(得分:0)

var final = {};
for (var i=0; i<data.length; i++){
  final[data[i].year] = final[data[i].year] || 0;
  final[data[i].year]++;
}

这将为您提供一个对象,其中年份为键,出现次数为值,如果尚未存在,则创建一个键值对。

如果您愿意,您可以创建一个包含所需属性的新数组:

var finalArray = [];
for (var key in final) {
    finalArray.push({year: key, frequency: final[key]});
}