我已经提供了一小段代码,你可以在控制台中运行来测试功能,并创建了一个演示函数,你可以立即使用(删除console.log语句)。它返回一个公司名称的数组。
实际上,我使用的是Javascript具有本地关联对象数组的事实,因此我将
toLowerCase
字段名(在您的情况下为公司)分配为关联数组查找点的字段。如果字段名尚未是属性,则这是我们第一次添加它。在第一次添加一个(考虑“bobo”)时,我们将其设置为零。在后续时间中,我们将其递增1。
function getCompaniesOver(companyArray, discountMinimum){
var tallyObject = {},
retArray = [],
has = Object.prototype.hasOwnProperty;
for(var k in companyArray){
var s = companyArray[k]+''; s = s.toLowerCase();
if (has.call(tallyObject,s)){
tallyObject[s]++;
} else {
tallyObject[s] = 0;
}
}
console.log(tallyObject);
console.log('companies with ' +companies_eligible_for_discount+ ' number of employees above 1 attending')
console.log('--------')
for (var k in tallyObject){
if (tallyObject[k] >= companies_eligible_for_discount){
console.log(k);
retArray.push(k);
}
}
console.log('--------')
return retArray;
}
var company_names_long = ['acme', 'acme', 'bobo', 'comanche', 'acme', 'comanche', 'comanche', 'acme', 'sanford & sons', 'Sanford & Sons', 'Johnson&Johnson', 'johnson&johnson'];
var company_names = ['acme', 'acme', 'bobo', 'comanche', 'acme', 'comanche'],
companies_eligible_for_discount = 2;
getCompaniesOver(company_names, companies_eligible_for_discount );
companies_eligible_for_discount = 1;
getCompaniesOver(company_names_long, companies_eligible_for_discount );